abinesh s abinesh s - 1 year ago 86
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 = '';
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.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 = '';
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.on('close', function() {
console.log('Connection closed');


CONNECTED: DATA I am Chuck Norris!


throw new TypeError('invalid data');

Answer Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download