如何知道何时完成 TCP 流的接收?
我不知道如何在 TCP 中判断发送者何时完成向我发送信息。
例如,如果A需要向B发送200个字节,B如何知道A已发送完毕,并且信息已准备好传输到应用层?
有 FIN 标志,但据我所知,它只是象征着你要关闭连接。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
TCP 没有义务告知接收方发送方何时完成了连接上的数据发送。它不能,因为它不了解它正在传输的更高级别的协议数据。
但是,它会告诉您连接是否关闭(然后您将在网络跟踪中看到 FIN、FIN-ACK)序列。从编程的角度来看,假设您使用的是 C,当对等方关闭连接时,函数 recv 将返回 0。
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.
您可以定义一个协议,例如首先以指定的字节顺序发送 4 字节 int,该顺序指示消息正文中将跟随多少字节。
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.
如果您使用的是 unix/linux,
select
和poll
可以向您发出信号,表明另一端已完成传输(已完成半/全关闭)。如果您已读取所有数据并希望从关闭的连接中读取,read
也会返回错误。如果您在一个连接上进行多次传输并希望发出“包”结束的信号,则必须将其构建到您的协议中。
If you're on unix/linux,
select
andpoll
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.