向 Node.js tcp 套接字发送多条消息时,它们会作为单个消息流式传输 [英] When sending multiple messages to a Node.js tcp socket, they get streamed as a single message

查看:24
本文介绍了向 Node.js tcp 套接字发送多条消息时,它们会作为单个消息流式传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了展示一个简单的例子,我想向一个 node.js tcp 套接字发送多条消息.我只想在第一条消息完全发送/耗尽时发送第二条消息.然而,即使在等待调用 write 回调时,这些消息似乎也是作为一条消息发送的.

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. However, even when waiting for the write callback to be invoked, the messages seem to be sent as one message.

这是一些示例代码:

var net = require('net');

var server = net.createServer();

server.on('connection', function(socket){
  socket.write('First Message', function(){
    socket.write('Second Message')
  })
})

var client = new net.Socket();
client.setEncoding('utf8');

server.listen(9999, function(){
  client.connect(9999);
});

client.on('data', function(data){
  console.log('data received on socket:\n' + data);
});

根据来自 socket.write 的 node.js 文档,可选的回调参数将在数据最终写出时执行 - 这可能不会立即执行."

According to the node.js documentation from socket.write, "The optional callback parameter will be executed when the data is finally written out - this may not be immediately."

基于此,在我的代码中,只有当第一条消息的数据最终写出时,才应发送第二条消息.

Based on this, in my code the second message should only be sent when the data is finally written out for the first message.

但是写入的输出是:

套接字接收到的数据:

第一条消息第二条消息

我怎样才能让它分别发送这些消息?

How can I get it to send these messages separately?

推荐答案

TCP 不会单独"发送消息.TCP 是一个stream 协议,这意味着当你向套接字写入字节时,你在接收端以相同的顺序获得相同的字节.没有任何消息边界"或数据包"的概念.

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.

在您的示例中,当套接字层接受您的数据进行传输时调用回调.它意味着数据已成功发送,甚至根本没有离开您的计算机.在您的回调中,您发送第二条消息,但套接字层将其与第一条消息结合以提高效率,因为它与 TCP 无关.

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.

这篇关于向 Node.js tcp 套接字发送多条消息时,它们会作为单个消息流式传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆