简体   繁体   中英

Convert TCP client from c# to nodejs

We are converting our TCP client written in c# code to nodejs.

The TCP client in c# is written as:

    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();
    }

The nodejs converted code is

     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();
        });
     });

This talk to a third party server. We are getting a correct response back from the server when using the c# while no response from nodejs

Not sure what I am missing. Please help

UPDATE:

I finally figured it out, after using WireShark to inspect the packets. The C# code was appending a NULL (ascii: 00) to the message while the nodejs code wasn't after appending a NULL value, the third party server started responding to the request

Try something like this, (I'm including a Node.js test server):

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');
});

You can test this out by running on the same machine and using the same PORT. Then you can try using another address ( and port). I think the issue with the previous code is that you were calling client.destroy straight after client.write. This causes an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM