Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message to individual client in node.js using only Net module(not socket.io)

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

  • How can I send a message to a specific client. From googling there are many socket.io related documents(solutions).. but, before using socket.io, I want to know node.js itself. (or javascript itself?)

  • 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);
    });
});
like image 362
ryuken73 Avatar asked Oct 27 '25 02:10

ryuken73


1 Answers

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');
like image 122
Vadim Baryshev Avatar answered Oct 28 '25 14:10

Vadim Baryshev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!