Linux上socket的缓冲是如何工作的
Linux 上的套接字如何进行缓冲? 即如果服务器不读取套接字并且客户端继续发送数据。 那么会发生什么呢?套接字的缓冲区有多大?客户端会知道并停止发送吗?
How does buffering work with sockets on Linux?
i.e. if the server does not read the socket and the client keeps sending data.
So what will happen? How big is the socket's buffer? And will the client know so that it will stop sending?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 UDP 套接字,客户端永远不会知道 - 服务器端将在接收缓冲区填满后开始丢弃数据包。
另一方面,TCP 实现流量控制。服务器的内核会逐渐缩小窗口,因此客户端能够发送的数据将越来越少。在某些时候,窗口将降至零。此时,客户端填满其发送缓冲区并从
send(2)
接收到错误。For UDP socket client will never know - the server side will just start dropping packets after the receive buffer is filled.
TCP, on the other hand, implements flow control. The server's kernel will gradually reduce the window, so the client will be able to send less and less data. At some point the window will go down to zero. At this point the client fills up its send buffer and receives an error from the
send(2)
.TCP 套接字使用协议栈中的缓冲。堆栈本身实现流量控制,因此如果服务器的缓冲区已满,它将阻止客户端堆栈发送更多数据。您的代码会将其视为对
send()
的阻塞调用。缓冲区大小变化很大,从几 kB 到几 MB。TCP sockets use buffering in the protocol stack. The stack itself implements flow control so that if the server's buffer is full, it will stop the client stack from sending more data. Your code will see this as a blocked call to
send()
. The buffer size can vary widely from a few kB to several MB.我假设您使用
send()
和recv()
进行客户端和服务器通信。因此,
send()
将返回已发送的字节数。这不一定等于您想要发送的字节数,因此您需要意识到这一点并发送其余部分。现在,
recv()
返回读取到缓冲区的字节数。所以如果recv返回0,那么服务器可能已经关闭了连接。I'm assuming that you're using
send()
andrecv()
for client and server communication.So,
send()
will return the number of bytes that have been sent out. This doesn't necessarily equal to to the number of bytes you wanted to send out, so it's up to you to realise this and send the rest.Now, the
recv()
returns the number of bytes read to the buffer. So if recv returns a 0, then the server has probably closed the connection.