如何限制我所连接的web套接字的消息流间隔



我认为没有必要在这里发布我的代码,但以防万一,我有它在下面。

我连接到coinbase websocket并试图拉硬币的价格,但消息流每秒多次为我提供数据,但我希望每分钟拉一次价格数据。

谁能帮助我了解如何使用WS节点包限制消息流?


const stream = new WebSocket('wss://ws-feed.exchange.coinbase.com')
stream.on('open', () => {
stream.send(JSON.stringify({
"type": "subscribe",
"product_ids": [
"BTC-USD"
],
"channels": [
{
"name": "ticker",
"product_ids": [
"BTC-USD"
]
}
]
}))
})

stream.on('message', (data) => {
console.log('received: ', JSON.parse(data))
})

为什么不在收到消息后关闭连接,然后在一分钟后重新连接呢?

<html>
<body>
<textarea rows="20" cols="100"  id="output"></textarea>
<script>
const output = document.querySelector('#output')
const MAX = 5;               // receive 5 messages
const INTERVAL =  60 *1000; // 1 minute                
const URL = 'wss://ws-feed.exchange.coinbase.com';
connect(URL);

function connect(addr) {                
let counter = 0;   // Track number of msgs received
let connection = new WebSocket(addr);
// no change to your code
connection.onopen = function() {
connection.send(JSON.stringify({
"type": "subscribe",
"product_ids": [
"BTC-USD"
],
"channels": [
{
"name": "ticker",
"product_ids": [
"BTC-USD"
]
}
]
}))
};

connection.onmessage =  function(event) {
output.value += `received: , ${ event.data}`;
counter++;
if ( counter == MAX ) {
counter = 0;    //reset counter
connection.close(); // no longer accept messages, 
output.value += "n*******nn"
setTimeout( function() { connect(URL); }, INTERVAL);   // reconnect after interval
}

};        
}

</script>
</body>
</html>

最新更新