nodejs套接字编程 – 发送数据长度

我有一个服务器监听特定的端口,并期望命令以下方式 –

前四个字节应该包含命令的长度,其余的字节包含实际的命令。 例如:

如果我想发送的命令是{cmd:"EL",ptno:1234} ,那么我发送的前四个字节应该以big-endian符号包含数字20,因为命令长度是20,因为命令是UTF -8格式。 我发送的剩余字节将包含命令。

我想知道如何在nodejs中做到这一点。 另外,当服务器发回数据时,我需要读取前四个字节并确定数据长度,并相应地读取套接字inputstream。 请帮忙。

我已经做了一个完全正确的,你需要的库: https : //www.npmjs.com/package/node-easysocket (除了在Little Endian中写入4个字节,但它很容易修复)

关于你的问题,在这里我们去:

为了发送消息,比接收更容易,只需要将消息转换为ByteArray,并且预先包含一个包含ByteArray + 4大小的整数(4字节Big Endian):

 var buffer = new Buffer("Hello World or a JSON String", "binary"); //create a buffer with +4 bytes var consolidatedBuffer = new Buffer(4 + buffer.length); //write at the beginning of the buffer, the total size consolidatedBuffer.writeInt32BE(buffer.length, 0); //Copy the message buffer to the consolidated buffer at position 4 (after the 4 bytes about the size) buffer.copy(consolidatedBuffer, 4); //Send the consolidated buffer socket.write(consolidatedBuffer, function(err) { if (err) console.log(err) }); 

如果你想阅读,它会更复杂一些,因为你有可能读取一个大块拼接的缓冲区。

例如:我的缓冲区大小为10MB,但是我的networking连接每秒钟可以传输大约100个字节,所以服务器会收到大量的数据,您需要将它们存储起来,直到按照第一个通知的长度4字节。

这个Javascript如果是一个dynamic语言,那么我可以创build一个运行时属性的socket对象来存储收集的块:

 socket.on('data', function(data) { console.log("server bytes in:"+data.length); receive(socket,data); }); function receive(socket, data){ //Create a chunk prop if it does not exist if(!socket.chunk){ socket.chunck = { messageSize : 0, buffer: new Buffer(0), bufferStack: new Buffer(0) }; } //store the incoming data socket.chunck.bufferStack = Buffer.concat([socket.chunck.bufferStack, data]); //this is to check if you have a second message incoming in the tail of the first var reCheck = false; do { reCheck = false; //if message size == 0 you got a new message so read the message size (first 4 bytes) if (socket.chunck.messageSize == 0 && socket.chunck.bufferStack.length >= 4) { socket.chunck.messageSize = socket.chunck.bufferStack.readInt32BE(0); } //After read the message size (!= 0) and the bufferstack is completed and/or the incoming data contains more data (the next message) if (socket.chunck.messageSize != 0 && socket.chunck.bufferStack.length >= socket.chunck.messageSize + 4) { var buffer = socket.chunck.bufferStack.slice(4, socket.chunck.messageSize + 4); socket.chunck.messageSize = 0; socket.chunck.bufferStack = socket.chunck.bufferStack.slice(buffer.length + 4); onMessage(socket, buffer); //if the stack contains more data after read the entire message, maybe you got a new message, so it will verify the next 4 bytes and so on... reCheck = socket.chunck.bufferStack.length > 0; } } while (reCheck); } function onMessage(socket, buffer){ console.log("message received from: "+socket+" with data:"+data.toString()+"); }