Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When sending multiple messages to a Node.js tcp socket, they get streamed as a single message

To show a simple example, I want to send multiple messages to a node.js tcp socket. I only want to send the second message when the first message is fully sent/drained. However, even when waiting for the write callback to be invoked, the messages seem to be sent as one message.

Here is some sample code:

var net = require('net');

var server = net.createServer();

server.on('connection', function(socket){
  socket.write('First Message', function(){
    socket.write('Second Message')
  })
})

var client = new net.Socket();
client.setEncoding('utf8');

server.listen(9999, function(){
  client.connect(9999);
});

client.on('data', function(data){
  console.log('data received on socket:\n' + data);
});

According to the node.js documentation from socket.write, "The optional callback parameter will be executed when the data is finally written out - this may not be immediately."

Based on this, in my code the second message should only be sent when the data is finally written out for the first message.

But the written output is:

data received on socket:

First MessageSecond Message

How can I get it to send these messages separately?

like image 572
Oved D Avatar asked Jun 09 '14 03:06

Oved D


1 Answers

You need to define a format for your message, so that your client can determine the beginning and end of a message within the socket stream. For instance, you could use a carriage return to mark the end of a message in your example.

Then you could use a split stream to read the messages separately in the client.

var net = require('net');
var split = require('split');
var server = net.createServer();

server.on('connection', function(socket){
  socket.write('First Message\n', function(){
    socket.write('Second Message\n')
  })
})

var client = new net.Socket();
client.setEncoding('utf8');

server.listen(9999, function(){
  client.connect(9999);
});

var stream = client.pipe(split());
stream.on('data',function(data){
    console.log(data);
});
like image 173
Edwin Dalorzo Avatar answered Sep 17 '22 12:09

Edwin Dalorzo