问题
Client blocks on the read call waiting to read n bytes.
Server writes n bytes and closes the connection immediately.
Can read call return negative or zero in this case if the socket gets closed before read is finished or due to some other issue? (client/server running on same linux box in this case)
I am facing such a scenario but not sure how this works in TCP/IP subsystem and how to resolve it.
Sever:
write
close
Client:
read
close
回答1:
The safe way to close a socket connection is first calling shutdown to signal that you won't be writing, keep reading the data that the remote side sends, and then shutdown the reading side and close the socket. If you close the socket before reading data sent to you the OS resets the connection (sends a packet with the RST flag set) and the remote side interprets this as an error.
回答2:
TCP treats the connection serially, and the reader processes everything in the order that the sender transmitted. When the sender closes the connection, the reader will get an EOF after it has read all the data that was sent, not before.
来源:https://stackoverflow.com/questions/17667901/how-to-handle-socket-read-in-c-when-the-remote-server-closes-socket-possibly-bef