Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: how to flush socket?

I'm trying to flush a socket before sending the next chunk of the data:

var net = require('net');

net.createServer(function(socket) {
    socket.on('data', function(data) {
        console.log(data.toString());
    });
}).listen(54358, '127.0.0.1');

var socket = net.createConnection(54358, '127.0.0.1');

socket.setNoDelay(true);
socket.write('mentos');
socket.write('cola');

This, however, doesn't work despite the setNoDelay option, e.g. prints "mentoscola" instead of "mentos\ncola". How do I fix this?

like image 311
Fluffy Avatar asked Jan 22 '12 00:01

Fluffy


1 Answers

Looking over the WriteableStream api, and the associated example it seems that you should set your breaks or delimiters yourself.

exports.puts = function (d) {
  process.stdout.write(d + '\n');
};

Because your socket is a stream, data will be written/read without your direct control, and #write won't change your data or assume you're meaning to break between writes, since you could be streaming a large piece of information over the socket and might want to set other delimiters.

I'm definitely no expert in this area, but that seems like the logical answer to me.

Edit: This is a duplicate of Nodejs streaming, and the conclusion there was the same as the answer I specified: working with streams isn't line-by-line, set your own delimiters.

like image 69
arbales Avatar answered Sep 22 '22 15:09

arbales