abinesh s abinesh s - 1 month ago 17
Node.js Question

Trying to write an Integer value through node js socket, but can't do that

Am trying to post some string from my tcp client to tcp server(Both were implemented using NodeJS). Once I receive message from client I need to write some integer value in the same socket. But when I tried writing the integer value, am getting an exception saying "Invalid Data". Can you please help me to understand or fix this.

Server Code:

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
sock.write(data.length);
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);


Client Code

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});

client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});

client.on('close', function() {
console.log('Connection closed');
});


Output:


CONNECTED: 127.0.0.1:56183 DATA 127.0.0.1: I am Chuck Norris!

net.js:612

throw new TypeError('invalid data');

Answer

The output says it all, invalid data!

request.write(chunk[, encoding][, callback])

The chunk argument should be a Buffer or a string.

sock is Stream, you can write Buffer or string into stream.

You should read the documentation of nodejs here https://nodejs.org/api/http.html#http_request_write_chunk_encoding_callback

What are you trying to achieve, communication between processes?