gpt4 book ai didi

node.js - nodejs套接字写入顺序

转载 作者:搜寻专家 更新时间:2023-10-31 23:10:11 25 4
gpt4 key购买 nike

在编写 nodejs 代理服务器时,我注意到在将数据写入另一个套接字端之前,数据可能会多次进入我的代理。每次我的数据进来时,我都会调用 socket.write(); ...

但是,由于发送的异步性质,我不确定 nodejs 是否保证传输数据的顺序与我安排写入的顺序相同。

有人知道nodejs在这种情况下的行为吗?

如果不能保证顺序,那么我将不得不缓冲数据,直到我收到数据成功发送的回调。

最佳答案

Node.js 是单线程的,一次只能做一件事。它有一个按顺序处理的回调队列。可以在此处找到更多信息:http://howtonode.org/understanding-process-next-tick .

只要您在接收数据时调用 socket.write,它就会按顺序到达。如果您考虑一下,如果它不这样做,那么 Node 将无法用作网络服务器。例如,一个简单的 node express 站点可能使用 fs.readfile 从磁盘异步读取文件并使用 socket.write 将其返回给浏览器。如果不能保证顺序,则可能无法正确返回该文件。

来自 Node 0.8.14 文档: http://nodemanual.org/latest/nodejs_ref_guide/net.html#net.Socket.write

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' is emitted when the buffer is again free.

net.Socket has the property that socket.write() always works. This is to help users get up and running quickly. The computer can't always keep up with the amount of data that is written to a socket—the network connection simply might be too slow. Node.js will internally queue up the data written to a socket and send it out over the wire whenever it's possible. (Internally, it's polling on the socket's file descriptor for being writable.)

关于node.js - nodejs套接字写入顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13855368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com