lundi 9 mars 2015

How to handle multiple incoming connections in Node.js?

I create a server with Node.js:



var net = require('net');

var PORT = 8181;

var server = net.createServer(

function(socket) {
console.log(this.address());

socket.on('data', function(data) {
var msg = data.toString().replace(/\n$/, '');
console.log('got: ' + msg);
});

process.stdin.on('readable',

function() {

var chunk = process.stdin.read();

if (chunk !== null) {

socket.write(chunk);
}
}
)

socket.write('heyyo\n');
}
)


Now, when multiple connections are coming in, this server sends out the typed in line only to the first connection.


I have two questions:




  • what is a standard way to handle this, i.e. to store the incoming sockets into an array?




  • exactly what happens that causes the readable event not to reach the other connections' callback function?




Aucun commentaire:

Enregistrer un commentaire