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

后端 未结 2 1292
广开言路
广开言路 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);
    });
    

提交回复
热议问题