If the client sends data and invokes close()
, and the server uses epoll_wait()
after a long time, causing the triggering of these two events (data arrival and connection closure) within the same epoll_wait()
, what will be the effect when I use recv()
to read data in this situation?
I know that recv()
returns 0 when the connection is closed and returns the number read when data comes, but what does it return in this case?
recv()
returns 0 when there is no more data to be received. Therefore, so long as there is data that could be received, it should not return 0.
So, if the client does send()
followed by close()
, assuming the send()
was sending a non-zero amount of data, then the TCP state will indicate there was some amount of data delivered followed by FIN
.
Even if the network delivered the FIN
out of order, the TCP sequence numbers will indicate that the FIN
is behind some amount of data, and TCP will wait for the arrival of that data. The client TCP state machine will retransmit if it does not see an acknowledgement of receipt from the server.
These are the reliable and in-order data delivery guarantees of the stream provided by TCP. So, the recv()
call on the server will not return 0 until after some other recv()
call consumes the data ahead of the FIN
.