O.Palm
O.Palm

Reputation: 162

How to send websocket messages in Node JS without libraries

i need help about to create a valid nodejs function that recieve an string or json and return data in the next format;

  0                   1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 +-+-+-+-+-------+-+-------------+-------------------------------+
 |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
 |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
 |N|V|V|V|       |S|             |   (if payload len==126/127)   |
 | |1|2|3|       |K|             |                               |
 +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
 |     Extended payload length continued, if payload len == 127  |
 + - - - - - - - - - - - - - - - +-------------------------------+
 |                               |Masking-key, if MASK set to 1  |
 +-------------------------------+-------------------------------+
 | Masking-key (continued)       |          Payload Data         |
 +-------------------------------- - - - - - - - - - - - - - - - +
 :                     Payload Data continued ...                :
 + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
 |                     Payload Data continued ...                |
 +---------------------------------------------------------------+

I did an native function for implement the upgrade websocket connection to stablish handshake and it's works. decode messages on server also work fine, but when i need send some message does not reach, i think that i don't compose a correct format data.

I want to avoid external libraries as "websocket", "socket.io", "ws" etc.. I need a native function and understand how to send little and bigger messages in this protocol from server.

Very thank's for your help

Upvotes: 0

Views: 441

Answers (1)

O.Palm
O.Palm

Reputation: 162

I found a way to get a code that seems work for little messages;

    var socket = this; // Or your socket "conn"
    var message = '.....'; // Or your string or json that you need send
    var bufferLength = (message.length > 125) ? 4 : 2;
    var preSend = Buffer.alloc(bufferLength);
    preSend[0] = 0x81;
    if (message.length > 125) {
        preSend[1] = 126;
        var length = message.length;
        preSend[2] = length >> 8;
        preSend[3] = length & 0xFF;
    }
    else {
        preSend[1] = message.length;
    }
    socket.write(preSend, 'binary');
    socket.write(message, 'utf8');

But, although this code seem work, i don't know if is valid for the websocket standard for little and bigger messages. Can somebody help me?

Upvotes: 1

Related Questions