套接字通信中send()和recv()的行为
以下是设置:
Server Client | | accept connect | | v | send msg1-> | | | v v recv <- send | | v v send msg2-> recv | | v v close
这是我的问题:
1.客户端在关闭之前其实就收到了msg1,为什么会这样?
2.发送msg2正常返回。既然客户端收到msg1后就关闭了,为什么发送msg2成功呢?
PS 我正在使用 TCP 流套接字。
The following is the setup:
Server Client | | accept connect | | v | send msg1-> | | | v v recv <- send | | v v send msg2-> recv | | v v close
Here is my question:
1. Client actually receives msg1 before it closes, why is it like this?
2. send msg2 returns normally. Since client closes after receiving msg1, why is send msg2 successful?
P.S. I'm using stream socket for TCP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
recv 函数将获取接收缓冲区中的下一个内容。对于客户端来说,如果套接字是数据报套接字,那么接下来是msg1。如果它是一个流套接字,则不会维护消息边界,因此如果 msg2 已到达并且在那里,recv 可能包含来自 msg1 和 msg2 的数据在recv 缓冲区中为两者提供了空间。
send
不会等待对方recv
消息,它只是将其添加到发送队列中。此时它不知道客户端是否会在读取连接之前关闭连接。如果您需要知道应该让客户端发送响应来确认消息。The
recv
function will get whatever is next in the receive buffer. In the case of the client, if the socket is a datagram socket, what is next is msg1. If it is a stream socket then message boundaries are not maintained so the recv could include data from both msg1 and msg2 if msg2 has arrived and there is room for both in the recv buffer.send
does not wait for the other side torecv
the message, it just adds it to the send queue. It does not know at that point whether the client will close the connection before reading it. If you need to know that you should have the client send a response to acknowledge the message.连接建立后,操作系统管理进入和离开系统的数据包,recv() 调用仅读取数据包缓冲区,send() 调用仅对数据包进行排队。
After your connection is set up, the OS manages the packets entering and leaving your system, the recv() call just reads the packet buffer, and the send() call just queues the packets.