Reputation: 783
Simple code:
process.stdin.resume()
process.stdin.setEncoding('utf8');
var server = createServer();
server.listen(9999);
server.on('connection',function(sock){
console.log('CONNECTED:'+sock.remoteAddress+":"+sock.remotePort);
process.stdin.on('data',function(send){
sock.write(send);
});
}
When receiving connection from 10.10.10.1 and 10.10.10.2, message "CONNECTED:10.10.10.1:xxx" and "CONNECTED:10.10.10.2:xxx" are display on terminal
To send message to a client, I used sock.write(send).. but, All clients received message
After reading Vadim's comment, I wrote down more code below. fully working code.
I add two things. According to Vadim's comment, add property sock.id
and using property sock.remoteAddress, send server's stdin message to
10.10.10.1 client only
var net = require('net')
process.stdin.resume()
process.stdin.setEncoding('utf8');
var server = net.createServer();
server.listen(9999);
server.on('connection',function(sock){
sock.write('input your ID: ',function(){
var setsockid = function(data){
id=data.toString().replace('\r\n','');
console.log('ID:'+id+' added!!')
sock.id=id
sock.removeListener('data',setsockid);
};
sock.on('data',setsockid);
sock.on('data',function(data){
d=data.toString().replace('\r\n','');
console.log(sock.id+' say: '+d);
});
});
console.log('CONNECTED:'+sock.remoteAddress+":"+sock.remotePort);
process.stdin.on('data',function(send){
if (sock.remoteAddress=='10.10.10.1') sock.write(send);
});
});
Upvotes: 4
Views: 6404
Reputation: 26219
Answer to your question is on Node.JS main page.
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
Upvotes: 4