我需要帮助创建一个有效的nodejs函数来接收字符串或json并以下一格式返回数据;
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 ... |
+---------------------------------------------------------------+
我做了一个原生函数,用于实现升级websocket连接到stablish握手及其工作。在服务器上解码消息也可以正常工作,但是当我需要发送一些消息无法到达时,我认为我不会撰写正确的格式数据。
我想避免将外部库作为" websocket"," socket.io"," ws"等等。我需要一个原生函数,并了解如何从服务器发送此协议中的小而大的消息。
非常感谢您的帮助
答案 0 :(得分:0)
我找到了一种方法来获取似乎适用于小消息的代码;
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');
但是,虽然这段代码似乎有用,但我不知道对于更小的和更大的消息是否对websocket标准有效。有人可以帮帮我吗?