When sending multiple messages to a Node.js tcp socket, they get streamed as a single message

后端 未结 2 1288
广开言路
广开言路 2021-02-02 17:37

To show a simple example, I want to send multiple messages to a node.js tcp socket. I only want to send the second message when the first message is fully sent/drained. Howeve

相关标签:
2条回答
  • 2021-02-02 18:10

    You need to define a format for your message, so that your client can determine the beginning and end of a message within the socket stream. For instance, you could use a carriage return to mark the end of a message in your example.

    Then you could use a split stream to read the messages separately in the client.

    var net = require('net');
    var split = require('split');
    var server = net.createServer();
    
    server.on('connection', function(socket){
      socket.write('First Message\n', function(){
        socket.write('Second Message\n')
      })
    })
    
    var client = new net.Socket();
    client.setEncoding('utf8');
    
    server.listen(9999, function(){
      client.connect(9999);
    });
    
    var stream = client.pipe(split());
    stream.on('data',function(data){
        console.log(data);
    });
    
    0 讨论(0)
  • 2021-02-02 18:31

    TCP does not send messages "separately". TCP is a stream protocol, which means that when you write bytes to the socket, you get the same bytes in the same order at the receiving end. There is no notion of "message boundaries" or "packets" anything of the sort.

    In your example, the callback is called when the socket layer accepts your data for transmission. It does not mean that the data has been successfully sent, or even that it has left your computer at all. In your callback, you send a second message, but the socket layer combines that with the first message for efficiency because it doesn't matter to TCP.

    0 讨论(0)
提交回复
热议问题