LoginSignup
1
1

More than 1 year has passed since last update.

TypeScript NodeJS websocket client

Last updated at Posted at 2021-09-09

install

npm i websocket @types/websocket

usage

共通化

const websocket = <T>(url: string, onmessage: (t: T) => void, onerror?: (e: any) => void, onclose?: () => void) => {
    const webClient = require("websocket").client
    const client: client = new webClient()
    client.on('connect', (con: connection) => {
        console.log(`connected ${con.connected}`)
        con.on('error', (e: any) => console.error(e))
        con.on('close', () => console.log("websockets closed."))
        con.on('message', (message: Message) => {
            if (message.type === "utf8") {
                const t = JSON.parse(message.utf8Data) as T
                onmessage(t)
            }
        })
        if (onerror) {
            con.on('error', onerror)
        }
        if (onclose) {
            con.on('close', onclose)
        }
    })
    client.connect(url)
}

利用例

この例では、仮想通貨取引所binanceへbtcusdt, xrpusdtの約定データをサブスクライブしている。

interface AggTrade {
    e: string
    E: number
    a: number
    s: string
    p: string
    q: string
    f: number
    l: number
    T: number
    m: boolean
}

function test(){
    websocket<AggTrade>("wss://fstream.binance.com/ws/" + "btcusdt@aggTrade", t => console.log(`Pare:${t.s}`))
    websocket<AggTrade>("wss://fstream.binance.com/ws/" + "xrpusdt@aggTrade", t => console.log(`Pare:${t.s}`))
    return
}
test()

実行結果

Pare:BTCUSDT
Pare:BTCUSDT
Pare:BTCUSDT
Pare:XRPUSDT
Pare:BTCUSDT
Pare:BTCUSDT
Pare:BTCUSDT
Pare:BTCUSDT
Pare:BTCUSDT
Pare:XRPUSDT
Pare:XRPUSDT
Pare:XRPUSDT
Pare:BTCUSDT

Document

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1