如何使用带有WebSockets的API(例如Kraken)



我正在尝试使用Websockets将REST API更新为API,但我不知道如何处理响应。

使用REST API和等待是很容易识别请求和响应。

但在WebSocket中,似乎所有的通信都是在onmessage中处理的,是混合的,我不知道如何识别它

如何在请求中识别没有id的具体答案?

例如,我连接到一个WebSockets API,在本例中为Kraken(exchange(,一旦连接打开,我就添加一个订单:

ws.send(JSON.stringify({
'event' : 'addOrder',
'ordertype' : 'limit',
'pair' : 'DAI/USD',
'price' : '0.005',
'token' : this.wsToken,
'type' : 'buy',
'volume' : '6',
}));

在onmessage中获得的响应可以是:

{"descr":"buy 6.00000000 DAIUSD @ limit 0.00500","event":"addOrderStatus","status":"ok","txid":"ABABC-ABABC-ABABC"}

请求没有Id,如果我启动10个addOrder和其他类型的请求,我就无法将请求与响应链接起来。

以这种方式使用API的逻辑是什么?

useEffect(() => {
new WebSocket('wss://ws.kraken.com').onopen = function () {
this.onclose = () => console.log('SOCKET CLOSED');
this.onmessage = (e) => console.log(JSON.parse(e.data));
this.send(
JSON.stringify({
event: 'subscribe',
pair: ['XBT/USD', 'XBT/EUR', 'ADA/USD'],
subscription: { name: 'ticker' },
}),
(e) => console.log(e),
);
};
}, [isPaused]);

相关内容

最新更新