Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将TCP客户端从c#转换为nodejs_C#_Node.js_Tcp - Fatal编程技术网

将TCP客户端从c#转换为nodejs

将TCP客户端从c#转换为nodejs,c#,node.js,tcp,C#,Node.js,Tcp,我们正在将用c#代码编写的TCP客户端转换为nodejs c#中的TCP客户端写为: using (TcpClient tcpClient = new TcpClient()) { tcpClient.Connect(HOST, port); NetworkStream stream = tcpClient.GetStream(); StreamWriter streamWriter = new StreamWriter((Stream)

我们正在将用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#代码在消息中添加了一个空值(ascii:00),而nodejs代码在添加了空值后没有添加空值,第三方服务器开始响应请求


您可以通过在同一台机器上运行并使用相同的端口来测试这一点。然后您可以尝试使用其他地址(和端口)。我认为前面代码的问题在于,您在client.write之后直接调用client.destroy。这会导致错误。

client.write('successfully sent the message')console.log('successfully sent the message')???是的。它应该是
console.log('successfully sent the message')我从c#和Nodejs代码中得到了相同的消息
var net = require('net');

var server = net.createServer(function(socket) {    
    socket.write('Hello from server!');

    socket.on('data', function(data) {
        console.log('Server: Received: ' + data);
    });
});

server.listen(PORT);

var client = new net.Socket();
client.connect(PORT, HOST, () => {
    console.log('Client: Connected to server.');
    var message = JSON.stringify({ "message" : "message" }) + '\r\n';
    client.write(message, () => {
       client.write('successfully sent the message\r\n' , () => {
           console.log("We're done with the client, closing..");
           client.end();
       });
    });
});

client.on('data', function(data) {
    console.log('Client: Received data: ' + data);
});

client.on('close', function() {
    console.log('Client: Connection closed');
});