I'm developing server application and have following problem with sending data back to client, that suddenly terminates the connection.
When I call send
on blocking socket with write timeout set via setsockopt(SO_SNDTIMEO)
and client disconnects during sending (i.e a few bytes are sent, then client properly terminates TCP - as can be seen in wireshark), send
still blocks, until send timeout elapses. Following call to send
returns error as expected.
I would expect that TCP termination (FIN/ACK) will cause blocking send
to return immediately, not after timeout.
Have someone ever seen such behaviour? Is it normal?
No, the FIN sent from the client does not unblock the send()
at the server. When the client calls close()
the FIN is sent to server and the connection is closed for the direction from client to server. The direction from server to client is still open till the server calls close()
and FIN is sent to the client.
When the client sends FIN and the server sends ACK back then connection on server is in the CLOSE_WAIT state and the connection on client is in the FIN_WAIT_2 state. Server still may send data and client still may receive data till server close the connection.
The close connection cannot be detected through send()
. Only recv()
detects the connection closed by peer.
If your code must execute an immediate action when client close the connection then it must call poll()
or select()
and use non-blocking send()
and recv()
calls.