问题描述
当我通过 tcp 流发送()/write() 一条消息时,如何确定这些字节是否已成功传递?
When i send()/write() a message over a tcp stream, how can i find out if those bytes were successfully delivered?
接收方通过 tcp 确认收到字节,因此发送方 tcp 堆栈应该知道.
The receiver acknowledges receiving the bytes via tcp, so the senders tcp stack should know.
但是当我 send() 一些字节时, send() 立即返回,即使数据包无法(尚未)传送,我在 linux 2.6.30 上使用 netcat 上的 strace 进行了测试,在发送之前拔出我的网线一些字节.
But when I send() some bytes, send() immediately returns, even if the packet could not (yet) be delivered, i tested that on linux 2.6.30 using strace on netcat, pulling my network cable out before sending some bytes.
我只是在开发一个应用程序,知道消息是否被传递非常重要,但是实现 tcp 功能(ack for message #123")感觉很尴尬,必须有更好的方法.
I am just developing an application where it is very important to know if a message was delivered, but implementing tcp features ("ack for message #123") feels awkward, there must be a better way.
推荐答案
发送 TCP 确实知道数据何时被另一端确认,但它这样做的唯一原因是它知道何时可以丢弃数据(因为现在有其他人负责将其传送到另一端的应用程序).
The sending TCP does know when the data gets acknowledged by the other end, but the only reason it does this is so that it knows when it can discard the data (because someone else is now responsible for getting it to the application at the other side).
它通常不会向发送应用程序提供此信息,因为(尽管表面上)它实际上对发送应用程序意味着.确认并不意味着接收应用程序已经获得了数据并对其进行了一些明智的处理——这只是意味着发送 TCP 不再需要担心它.数据可能仍在传输中 - 例如在中间代理服务器内,或在接收 TCP 堆栈内.
It doesn't typically provide this information to the sending application, because (despite appearances) it wouldn't actually mean much to the sending application. The acknowledgement doesn't mean that the receiving application has got the data and done something sensible with it - all it means is that the sending TCP no longer has to worry about it. The data could still be in transit - within an intermediate proxy server, for example, or within the receiving TCP stack.
成功接收数据"实际上是一个应用程序级别的概念 - 它的含义因应用程序而异(例如,对于许多应用程序,只有在将数据同步到磁盘后才考虑接收到"数据才有意义在接收方).所以这意味着您必须自己实现它,因为作为应用程序开发人员,您确实是唯一知道如何为您的应用程序明智地实现它的人.
"Data successfully received" is really an application-level concept - what it means varies depending on the application (for example, for many applications it would only make sense to consider the data "received" once it has been synced to disk on the receiving side). So that means you have to implement it yourself, because as the application developer, you're really the only one in a position to know how to do it sensibly for your application.
这篇关于查明是否通过 tcp 传递了一条消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!