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?

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. 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)... Commented Jun 17, 2011 at 1:24

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.