How to handle socket read in C when the remote server closes socket possibly before read is finished?

五迷三道 提交于 2019-12-08 02:50:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!