开发者

The behavior of send() and recv() in socket communication

开发者 https://www.devze.com 2022-12-26 09:11 出处:网络
The following is the setup: ServerClient acceptconnect v| send msg1->| vv recv<-send v开发者_StackOverflowv

The following is the setup:

Server         Client
 |                |
accept         connect
 |                |
 v                |
send msg1->       | 
 |                |
 v                v
recv    <-     send
 |                |
 v  开发者_StackOverflow              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.


  1. 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.

  2. send does not wait for the other side to recv 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号