5

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?

Mickey Shine
  • 12,187
  • 25
  • 96
  • 148
  • 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 Jun 02 '11 at 04: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 Jun 17 '11 at 01:24

1 Answers1

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);
maerics
  • 151,642
  • 46
  • 269
  • 291