如何使用node.js构架用于通过TCP发送的消息? [英] How do I frame messages for sending over TCP with node.js?
问题描述
我需要从node.js TCP服务器向多个TCP客户端发送JSON字符串.
I need to send a JSON string to a number of TCP clients from a node.js TCP server.
为了从客户端的套接字/流中读取消息,我需要执行某种消息框架.一种方法是在消息的长度之前将消息的长度作为数组前缀-然后在客户端将其转换为消息的缓冲区大小.
In order to read the messages from the socket/stream on the client side I need to do some sort of message framing. One way to do this is to prefix the message with the length of the message as an array - then convert that to the buffer size for the message on the client side.
我该如何在服务器上的node.js/javascript中执行类似的操作,然后使用.NET客户端在客户端将其读出?
How would I do something like this in node.js/javascript on the server and then read it out on the client side using a .NET client?
鉴于此客户端代码,我如何使用javascript/node在服务器端正确构建消息?
Given this client side code, how would I frame the message correctly on the server side using javascript/node?
TcpClient client = new TcpClient(server, port);
var netStream = client.GetStream();
// read the length of the message from the first 4 bytes
byte[] b = new byte[4];
netStream.Read(b, 0, b.Length);
int messageLength = BitConverter.ToInt32(b, 0);
// knowing the length, read the rest of the message
byte[] buffer = new byte[messageLength];
netStream.Read(buffer, b.Length, buffer.Length);
var message = System.Text.Encoding.UTF8.GetString(buffer);
推荐答案
以便在Node.js中解包传入的数据,您可以尝试使用节点缓冲区 或手动创建自己的 FSM 并将其与传入的数据块一起输入
to unframe incoming data in nodejs you can try to use node-bufferlist or node-buffers or create your own FSM manually and feed it with incoming chunks of data
服务器端更简单:
function sendPacket(stream, buffer)
{
var prefix = new Buffer(4);
var length = buffer.length;
var offset = 0;
// serialize 32bit little endian unsigned int
prefix[offset++] = length & 0xff;
prefix[offset++] = (length >> 8) & 0xff );
prefix[offset++] = (length >> 16) & 0xff );
prefix[offset++] = (length >> 24) & 0xff );
stream.write(prefix);
stream.write(buffer);
}
或者您可以使用节点v0.5 + buffer.writeUInt32
or you can use node v0.5+ buffer.writeUInt32
这篇关于如何使用node.js构架用于通过TCP发送的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!