Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 634
Mickey Shine Avatar asked Jun 02 '11 03:06

Mickey Shine


People also ask

How do I send data from server to client in node?

Methods to send response from server to client are:Using send() function. Using json() function.

How do I send HTTP POST request in node?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.


1 Answers

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);
like image 157
maerics Avatar answered Oct 04 '22 02:10

maerics