RSwan RSwan - 2 years ago 180
Node.js Question

TCP socket.write function in node.js' "net" package not writing to socket

I am having some trouble writing 2 messages to a TCP socket using node.js' net package.

The code:

var net = require('net');

var HOST = '';
var PORT = '5555';

var socket = new net.Socket();

socket.connect (PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client


// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
socket.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
// client.destroy();

socket.on('error', function(exception){

socket.on('drain', function() {

socket.on('timeout', function() {

// Add a 'close' event handler for the client socket
socket.on('close', function() {
console.log('Connection closed');

I've also tried the supposedly more correct net.createConnection(arguments...) function from the net package with no luck.

I can see on my server side that the connection to the socket happens just as expected but there is no data received by the server which is why I'm suspecting that something is wrong with the way I'm using the socket.write function. Perhaps the first strings characters are causing confusion?

Any help would be greatly appreciated.

Many thanks.

Answer Source

It depends on what server you are speaking to, obviously, but you should probably delimit your data with newlines \n:


For some servers, you might need \r\n.

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