从 Unix SOCK_STREAM 套接字读取大量数据
我是异步 I/O 新手。 我需要从 Unix SOCK_STREAM 套接字读取大量数据。我正在使用非阻塞套接字。 它可能需要多个 read/recv()。那部分对我来说很好。
我的疑问是—— 如果一次有 3-4 个客户端向我的服务器套接字写入大量数据,则假设每个客户端写入 100K 数据。 是否可能出现这样的情况:我的第一次读取是从 client1 读取一些数据(例如 40 K),第二次读取是从 client 2 读取数据,第三次读取再次从 client1 读取剩余数据?
问候 DJ
I am new to asynchronous I/O.
I need to read a big chuck of data from Unix SOCK_STREAM socket.I am using non-blocking socket.
It may require more than one read/recv(). That part is fine with me.
My doubt is --
If at a time 3-4 clients are writing huge data to my server socket say each one is writing 100K data.
Is it can be a scenario where my first read is reading some data(say 40 K) from client1 and second read is reading data from client 2 and third read is again reading remaining data from client1?
Regards
DJ
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您问题的答案很大程度上取决于您如何定义 client1 到 clientN。具体来说,他们如何形成与服务器的连接。
SOCK_STREAM 是面向连接的。这意味着您的服务器创建一个侦听套接字,绑定到它,然后当客户端连接时,服务器接受该连接并本质上获得一个新套接字。
现在,如果 client1 到 clientN 将分别进行单独的连接,则服务器基本上将有 N 个不同的套接字,在这种情况下,您的问题的答案是否定的 - 来自不同客户端的数据不会混合,因为它们是在不同的套接字上传输的。
但是,如果您有这样的安排,即您有一个打开连接的父客户端,并且该套接字由客户端 1 到 n 共享(例如在不同的线程或子进程中),那么答案是肯定的 - 在特定套接字上写入不是原子的,数据可以混合。
顺便说一句,如果您使用 Unix 管道而不是 Unix 域套接字,即使同一管道上有不同的写入者,您也将获得原子写入的好处,达到某个阈值(根据 POSIX 至少为 512,Linux 实际上支持65000字节)
The answer to your question very much depend on how you define client1 to clientN. Specifically, how do they form the connection to the server.
A SOCK_STREAM is connection oriented. This means that your server creates a listening socket, binds to it and then when the client connects the server accepts the connection and gets in essence a new socket.
Now, if client1 to clientN will each do a seperate connection the server will basically have N different sockets, In this case, the answer to your questions is no - data from the different clients will not mix since they are being transmitted on different sockets.
However, if you have the sort of arrangement where you have a father-client that opens the connection and that socket is shared by clients1 to n (say in different threads or child processes) then the answer is yes - the writes on a specific socket are not atomic and the data can mix.
As a side note, if you use a Unix pipe rather then a unix domain socket, you will get the benefit of writes being atomic even with different writers on the same pipe uo to a certain threshold (at least 512 according to POSIX, Linux actually supports 65000 bytes)