最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to send data to a specified connection while using node.js - Stack Overflow

programmeradmin0浏览0评论

I am using node.js building a TCP server, just like the example in the doc. 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?

I am using node.js building a TCP server, just like the example in the doc. 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?

Share asked Jun 2, 2011 at 3:41 Mickey ShineMickey Shine 12.6k26 gold badges97 silver badges151 bronze badges 2
  • That's just not the typical server idiom. Servers sit around waiting for a message from a client, act on such messages when they arrive, and then wait some more. If a server sends a message to a client without the client having sent a message to the server, there is no guarantee that the client is even listening for messages from the server. – Matt Ball Commented Jun 2, 2011 at 4:09
  • 2 @Matt Ball: that's the case for HTTP servers, definitely, but general TCP client/server applications can run any protocol they want, including ones wherein the server sends "unsolicited" messages to the client(s)... – maerics Commented Jun 17, 2011 at 1:24
Add a ment  | 

1 Answer 1

Reset to default 8

Your server could maintain a data structure of active connections by adding on the server "connection" event and removing on the stream "close" event. 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);
发布评论

评论列表(0)

  1. 暂无评论