Denim Demon
Denim Demon

Reputation: 734

Reading a clients data input in a NodeJS TCP Server

Im trying to create a NodeJS TCP Server, that will read to the clients input and then act accordingly.

I'd like to know how I can read the data, so I can set up conditionals to perform process.

var net = require('net');
var server = net.createServer(function (socket) {

socket.on('data', function(data) {
    buf = new Buffer(256);
    len = buf.write(data.toString());

    if (buf.toString('utf8', 0, len) === "test"){
        console.log("you typed test");
    }

    console.log(len + " bytes: " + buf.toString('utf8', 0, len));
});
socket.write("Connected to server.\r\n");
});
server.listen(8080, "127.0.0.1");

I am outputting the value inputted here : console.log(len + " bytes: " + buf.toString('utf8', 0, len)); but my if statement above this log, isnt matching the value 'test' when I actually type 'test' in the client terminal window.

Any help is appreciated

-chris

Upvotes: 3

Views: 5847

Answers (1)

Denim Demon
Denim Demon

Reputation: 734

I worked it out using the toString() method:

socket.on('data', function(data) {
  var response = data.toString().trim();

  if (/disconnect/.test(response)) {
    console.log("Client is diconnecting.");
    socket.end('Disconnecting you now.\r\n');
  } 
});

socket.on('end', function() {
  console.log('client disconnected');
});

Upvotes: 6

Related Questions