tags:

views:

127

answers:

2

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.

+3  A: 
  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.

mark4o
Why is data received before recv() is called? I think recv() isn't called until send() has finished, but msg1 is sent by server before send() has finished.
gc
The TCP stack takes care of sending/receiving the data. you do not have to call recv() for the OS to receive the data - atleast not until to internal buffers of the OS is full. Keep in mind that TCP is stream based as well, not message oriented - one send() call might need several recv() call to receive and vice versa.
nos
When the data arrives from the network, the OS buffers it until your application calls `recv()`. Several packets may have arrived by that time, and your application can get all the data at once with a single call to `recv()`. If you do not call `recv()` it will keep buffering the data until the receive window is full. Then you will have to call `recv()` to make room for more data.
mark4o
+3  A: 

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.

Spidey