如何使用WebSocket不断更新和推送数据?

时间:2018-11-01 12:50:51

标签: javascript websocket

我有一个ws.js是我的服务器:

// A simple server-side script.
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 3000 });

let number = 0.0;

function updateNumber(){
    number = Math.random().toFixed(4);
}

// Desperetly tried this.
var emitter = function() {}

var emission = function(data) {
  emitter(data);
}

// Then my WebSocket stuff.
wss.on('connection', function(ws) {
    emitter = function(data) {
        wss.clients.forEach(function(client) {
            // ---> How to constantly run updateNumber()
            // As long as connection is live.
            console.log(data);
            // Debug
            console.log('[server:onConnect] Received request.');
            // Send the transmission.
            console.log('[server:onConnection] Sending:', number);
            client.send(number);
        });
    }
});

我必须不使用setInterval()来执行此操作,因为数字将来自不断更新的文件。

因此,在服务器的详细信息流中,一旦客户端连接到终端,我就会得到以下信息:

[server:onConnection] Sending: 0.9569
[server:onConnect] Received request.
[server:onConnection] Sending: 0.4058
[server:onConnect] Received request.
[server:onConnection] Sending: 0.7813
[server:onConnect] Received request.
[server:onConnection] Sending: 0.9672
[server:onConnect] Received request.
[server:onConnection] Sending: 0.0671
[server:onConnect] Received request.
[server:onConnection] Sending: 0.5682
[server:onConnect] Received request.
[server:onConnection] Sending: 0.0171

---更新---

当我将updateNumber()函数调整为:

时,此问题已解决。
function updateNumber(){
    number = Math.random().toFixed(4);
    emission();
}

这似乎已成功桥接了emitter块和on connect函数内部的updateNumber()函数。

但是,此解决方案仍然需要setInterval()来运行updateNumber(),以便发出不断变化的数字。有没有一种方法可以创建一个运行并不断发出随机数的函数,而无需使用setInterval()

1 个答案:

答案 0 :(得分:0)

https://www.linode.com/docs/development/introduction-to-websockets/

本文可以帮助您正确理解websocket以及如何在不使用setInterval的情况下监听函数