如何在使用node.js时将数据发送到指定的连接

Mic*_*ine 5 javascript tcp http node.js

我正在使用node.js构建TCP服务器,就像doc中的示例一样.服务器建立持久连接并处理客户端请求.但我还需要将数据发送到任何指定的连接,这意味着此操作不是由客户端驱动的.怎么做?

mae*_*ics 8

您的服务器可以通过在服务器上添加"连接"事件并在流"close"事件上删除来维护活动连接的数据结构.然后,您可以从该数据结构中选择所需的连接,并随时将数据写入其中.

下面是一个时间服务器的简单示例,它每秒向所有连接的客户端发送当前时间:

var net = require('net')
  , clients = {}; // Contains all active clients at any time.

net.createServer().on('connection', function(sock) {
  clients[sock.fd] = sock; // Add the client, keyed by fd.
  sock.on('close', function() {
    delete clients[sock.fd]; // Remove the client.
  });
}).listen(5555, 'localhost');

setInterval(function() { // Write the time to all clients every second.
  var i, sock;
  for (i in clients) {
    sock = clients[i];
    if (sock.writable) { // In case it closed while we are iterating.
      sock.write(new Date().toString() + "\n");
    }
  }
}, 1000);
Run Code Online (Sandbox Code Playgroud)