简体   繁体   English

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

[英]How to send data to a specified connection while using node.js

I am using node.js building a TCP server, just like the example in the doc.我正在使用 node.js 构建 TCP 服务器,就像文档中的示例一样。 The server establishes persistent connections and handle client requests.服务器建立持久连接并处理客户端请求。 But I also need to send data to any specified connection, which means this action is not client driven.但我还需要将数据发送到任何指定的连接,这意味着此操作不是客户端驱动的。 How to do that?怎么做?

Your server could maintain a data structure of active connections by adding on the server "connection" event and removing on the stream "close" event.您的服务器可以通过添加服务器“连接”事件并删除 stream“关闭”事件来维护活动连接的数据结构。 Then you can pick the desired connection from that data structure and write data to it whenever you want.然后,您可以从该数据结构中选择所需的连接,并随时向其写入数据。

Here is a simple example of a time server that sends the current time to all connected clients every second:这是一个简单的时间服务器示例,它每秒向所有连接的客户端发送当前时间:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM