【发布时间】:2011-10-02 18:42:43
【问题描述】:
我需要从 node.js TCP 服务器向多个 TCP 客户端发送 JSON 字符串。
为了从客户端的套接字/流中读取消息,我需要进行某种消息框架。一种方法是在消息前面加上消息长度作为数组的前缀 - 然后将其转换为客户端消息的缓冲区大小。
我将如何在服务器上的 node.js/javascript 中执行类似的操作,然后使用 .NET 客户端在客户端读取它?
鉴于此客户端代码,我将如何使用 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);
【问题讨论】: