javascript - node js read specific message from tcp socket net.createServer -


var net = require('net');  var host = '0.0.0.0'; var port = 5000;  // create server instance, , chain listen function // function passed net.createserver() becomes event handler 'connection' event // sock object callback function receives unique each connection net.createserver(function(sock) {  // have connection - socket object assigned connection automatically console.log('connected: ' + sock.remoteaddress +':'+ sock.remoteport);  // add 'data' event handler instance of socket sock.on('data', function(data) {      console.log('data ' + sock.remoteaddress + ': ' + data);     // write data socket, client receive data server     if (data === "exit") {         console.log('exit message received !')     }  });  // add 'close' event handler instance of socket sock.on('close', function(data) {     console.log('closed: ' + sock.remoteaddress +' '+ sock.remoteport); });  }).listen(port, host);  console.log('server listening on ' + host +':'+ port); 

no matter try, cannot get:

    if (data === "exit") {         console.log('exit message received !')     } 

working, it's false.

i'm connecting via telnet , sending "exit", server should go "if" loop , "exit message received". never happens, can shed light ? thanks

that's because data not string, if try compare === false because types don't match. solve should compare data object simple == or use socket.setencoding('utf8') previous binding data event.

https://nodejs.org/api/net.html#net_event_data

var net = require('net'); var host = '0.0.0.0'; var port = 5000;  net.createserver(function(sock) {     console.log('connected:',sock.remoteaddress,':',sock.remoteport);     sock.setencoding("utf8"); //set data encoding (either 'ascii', 'utf8', or 'base64')     sock.on('data', function(data) {         console.log('data',sock.remoteaddress,': ',data,typeof data,"===",typeof "exit");         if(data === "exit") console.log('exit message received !');     });  }).listen(port, host, function() {     console.log("server accepting connections"); }); 

note. if data received going big should concatenate , handle message comparison @ end of it. check other questions handle cases:

node.js net library: getting complete data 'data' event


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -