Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = '20.100.2.62';
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 
  socket.write('@!>');       
  socket.write('RIG,test,test,3.1');

});



// 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){
  console.log('Exception:');
  console.log(exception);
});


socket.on('drain', function() {
  console.log("drain!");
});

socket.on('timeout', function() {
  console.log("timeout!");
});

// 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.

like image 925
RSwan Avatar asked Feb 17 '12 13:02

RSwan


People also ask

How do you write data into a socket?

The write() call writes data from a buffer on a socket with descriptor fs . The write() call can only be used with connected sockets. This call writes up to N bytes of data. write() is equivalent to send() with no flags set.

How do I run a socket program in node js?

// make a connection with the user from server side io. on('connection', (socket)=>{ console. log('New user connected'); }); Similarly, from the client-side, we need to add a script file and then make a connection to a server through which users send data to a server.

Does node js use TCP?

Node. js is used for building server-side and networking applications. TCP (Transmission Control Protocol) is a networking protocol that provides reliable, ordered and error-checked delivery of a stream of data between applications.


1 Answers

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

socket.write('@!>\n');       
socket.write('RIG,test,test,3.1\n');

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

like image 139
Linus Thiel Avatar answered Nov 02 '22 06:11

Linus Thiel