简体   繁体   English

将Node.js net.socket与流消息协议一起使用

[英]Using Node.js net.socket with a streaming message protocol

I have a C++ server process I'm trying to connect to over TCP which uses a simple stream protocol. 我有一个C ++服务器进程,试图通过使用简单流协议的TCP连接到该服务器。 The first 8 bytes of the packet is the message length in bits and then the rest of the packet is the actual message as a string. 数据包的前8个字节是消息的长度(以位为单位),然后数据包的其余部分是作为字符串的实际消息。 A C++ client process which connects to said server constructs messages for it like this: 连接到所述服务器的C ++客户端进程为此构建消息,如下所示:

char* msgBuff = new char[msgLen + sizeof(int)];
int nlen = htonl(msgLen);
memcpy(msgBuff, &nlen, sizeof(int));
memcpy(msgBuff + sizeof(int), msg, msgLen);

So I'm trying to do the same in node.js. 所以我试图在node.js中做同样的事情。 I have my message string and I wrote my own version of htonl by converting a msglen var into a string representing the correct byte swapped hex value. 我有消息字符串,并通过将msglen var转换为表示正确的字节交换十六进制值的字符串来编写自己的htonl版本。 Then I do parseInt with that string to get the var as a hex value: 然后,我使用该字符串执行parseInt以将var作为十六进制值获取:

var byteSwappedMsgLen = parseInt(lengthAsAString,16);

And then I try to write this and my msg to my net.socket like this: 然后我尝试像这样将这和我的消息写到net.socket:

soc.write(byteSwappedMsgLen + msg);

But something is wrong. 但是出了点问题。 My msg length of 210 which is 000000d2 in hex gets byteswapped by my function so that lengthAsAString=d2000000. 我的msg长度210(十六进制为000000d2)被我的函数字节交换,因此lengthAsAString = d2000000。 But for some reason when I print byteSwappedMsgLen to the console it's equal to 3523215360. The C++ server reads it as a message length of 859124275. So I'm not sure if I'm not converting the string correctly and\\or if I'm not constructing the message properly. 但是由于某些原因,当我在控制台上打印byteSwappedMsgLen时,它等于3523215360。C++服务器将其读取为消息长度为859124275。因此,我不确定是否未正确转换字符串和/或无法正确构造消息。

Figured out I need to use Buffers and pad the hex value with leading zeros (no need to byte swap). 弄清楚我需要使用缓冲区,并用前导零填充十六进制值(无需字节交换)。

var buffer = new Buffer(msg.length + 4);
buffer.write(paddy(msg.length.toString(16),8),'hex');
buffer.write(msg,4,'ascii');
s.write(buffer);

//found this function elsewhere
function paddy(n, p, c) {
    var pad_char = typeof c !== 'undefined' ? c : '0';
    var pad = new Array(1 + p).join(pad_char);
    return (pad + n).slice(-pad.length);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM