How to know when you finish receiving a TCP stream?

亡梦爱人 提交于 2019-12-24 08:56:39

问题


I'm not sure how to tell in TCP when the sender finished sending me the information.

For example if A needs to send 200 bytes to B, how will B know that A finished sending, and that the information is ready to be transferred to the application layer?

There's the FIN flag, but as far as I know it's only there to symbolizes that your going to close the connection.

Thanks.


回答1:


TCP has no obligation to tell the receiver when the sender has finished sending data on the connection. It can't because it has no understanding of the higher level protocol data it's transporting.

However it will tell you if the connection closes (then you'll see a FIN, FIN-ACK) sequence in a network trace. From a programming perspective, assuming that you're using C the function recv will return 0 when the peer closes the connection.




回答2:


If you're on unix/linux, select and poll can signal you that the other end finished transfer (did a half/full close). read will also return with an error if you've read all the data and want to read from a closed connection.

If you do multiple transfers on one connection and want to signal the end of a "package" you have to build that into your protocol.




回答3:


You define a protocol such as first sending a 4 byte int in a specified byte order which indicates how many bytes will follow in the message body.



来源:https://stackoverflow.com/questions/7522965/how-to-know-when-you-finish-receiving-a-tcp-stream

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