我正在编写一个节点服务器,我需要将一个32位整数发送到c#客户端(作为标题)。
我不太清楚如何做到这一点,因为位移操作员让我感到困惑。我认为我的c#客户端希望这些整数采用小端格式(我不确定,我说是因为NetworkStream
IsLittleEndian属性为真。)
所以说我在javascript中有一个类似
的变量var packetToDeliverInBytes = GetByteArrayOfSomeData();
//get the integer we need to turn into 4 bytes
var sizeOfPacket = packetToDeliver.length;
//this is what I don't know how to do
var bytes = ConvertNumberTo4Bytes(sizeOfPacket)
//then somehow do an operation that combines these two byte arrays together
//(bytes and packetToDeliverInBytes in this example)
//so the resulting byte array would be (packetToLiver.length + 4) bytes in size
//then send the bytes away to the client
socket.write(myByteArray);
如何编写ConvertNumberTo4Bytes()函数?
加成
如何将这两个字节数组合并为一个,这样我就可以在一个socket.write调用中发送它们
答案 0 :(得分:1)
感谢elclanrs评论,在节点中使用Buffer
对象似乎是要走的路。
var buf = new Buffer(4 + sizeOfPacket);
buf.writeInt32LE(sizeOfPacket, 0);
buf.write(packetToDeliverInBytes, 4);
socket.write(buf);