yosh
yosh

Reputation: 123

Sending socket data separately in node.js

I'm now trying to send bytes continuously from node.js(server) to Android(client). Let me show the code example.

var net = require('net');
var server = net.createServer(function(c){
    c.on('data', function(data){
        if(data == 'foo'){
            for(var i = 1; i <= 255; i++){
                var byteData = makeBytedata();
                c.write(byteData);
                wait(100)
            }
        }
    });
});

This code does not works fine because it sometimes combines byteData to one packet. Does anyone have solution to send bytes separately?

Upvotes: 0

Views: 754

Answers (1)

zangw
zangw

Reputation: 48356

net.createServer create TCP server, TCP does not send messages separately. TCP is a stream protocol, which means that when you write bytes to the socket, you get the same bytes in the same order at the receiving end.

One work around: define a format for your message, so that your client can determine the beginning and end of a message within the socket stream. For example, you could use a \n to mark the end of a message.

   for(var i = 1; i <= 255; i++){
        var byteData = makeBytedata();
        c.write(byteData + '\n');
    }

Then the client could separate them by \n.

The other way could be to use UDP/Dgram

var dgram = require("dgram"),
    server = dgram.createSocket('udp4');

server.on("message", function(msg, rinfo) {
    // send message to client 
});

Upvotes: 1

Related Questions