Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9409

TypeScript NodeJS websocket client

$
0
0
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

Viewing all articles
Browse latest Browse all 9409

Trending Articles