How to pass messages for sending over TCP using node.js?

I need to send a JSON string to multiple TCP clients from node.js.s TCP server

To read messages from a socket / stream on the client side, I need to do some message processing. One way to do this is to prefix the message with the length of the message as an array, and then convert it to the size of the buffer for the message on the client side.

How can I do something like this in node.js / javascript on the server and then read it on the client side using a .NET client?

Given this client-side code, how do I correctly create a server-side message using javascript / node?

        TcpClient client = new TcpClient(server, port);
        var netStream = client.GetStream();

        // read the length of the message from the first 4 bytes
        byte[] b = new byte[4];
        netStream.Read(b, 0, b.Length);
        int messageLength = BitConverter.ToInt32(b, 0);

        // knowing the length, read the rest of the message
        byte[] buffer = new byte[messageLength];
        netStream.Read(buffer, b.Length, buffer.Length);
        var message = System.Text.Encoding.UTF8.GetString(buffer);
+5
source share
1 answer

nodejs, node-bufferlist node-buffers FSM

:

function sendPacket(stream, buffer)
{
    var prefix = new Buffer(4);
    var length = buffer.length;
    var offset = 0;
    // serialize 32bit little endian unsigned int
    prefix[offset++] = length & 0xff;
    prefix[offset++] = (length >> 8)  & 0xff );
    prefix[offset++] = (length >> 16)  & 0xff );
    prefix[offset++] = (length >> 24)  & 0xff );
    stream.write(prefix);
    stream.write(buffer);
}

node v0.5 + buffer.writeUInt32

+3

All Articles