【发布时间】:2018-09-05 11:10:09
【问题描述】:
我们正在将用 c# 代码编写的 TCP 客户端转换为 nodejs。
c#中的TCP客户端写成:
using (TcpClient tcpClient = new TcpClient())
{
tcpClient.Connect(HOST, port);
NetworkStream stream = tcpClient.GetStream();
StreamWriter streamWriter = new StreamWriter((Stream)stream);
string str = "{ \"message\" : \"" + message + "\" }";
streamWriter.Write(str);
streamWriter.Flush();
int num = 0;
stream.WriteByte((byte)num);
tcpClient.Close();
}
nodejs转换后的代码是
var client = new net.Socket();
client.connect(PORT, HOST, function () {
var command = { "message" : "message" };
var message = JSON.stringify(command);
client.write(message, function () {
client.write('successfully sent the message');
client.destroy();
});
});
这与第三方服务器对话。使用 c# 时,我们从服务器得到正确的响应,而 nodejs 没有响应
不知道我错过了什么。请帮忙
更新:
在使用 WireShark 检查数据包后,我终于弄明白了。 C# 代码将 NULL (ascii: 00) 附加到消息中,而 nodejs 代码在附加 NULL 值后没有,第三方服务器开始响应请求
【问题讨论】:
-
client.write('successfully sent the message');你真的想把这个也写到行吗? -
我会这样做: 1. 使用 Wireshark 之类的工具检查是否有消息,如果有,它与 C# 的不同之处。 2. 检查服务器日志是否收到消息以及是否有异常。
-
也许你的意思是
console.log('successfully sent the message');??? -
是的。它应该是
console.log('successfully sent the message');