有没有办法阻止套接字发送(),直到我们得到该数据包的确认? [英] Is there a way to block on a socket send() until we get the ack for that packet?

查看:9
本文介绍了有没有办法阻止套接字发送(),直到我们得到该数据包的确认?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还是我必须在应用程序级别实现它?

Or do I have to implement it at the application level?

推荐答案

几周前我在实现 VoIP 服务器时也遇到了同样的问题.花了几天后,我可以想出一个解决方案.正如许多其他人提到的,没有任何直接的系统调用来完成这项工作.相反,

I also faced the same problem few weeks ago when implementing a VoIP server. After spending several days I could come up with a solution. As many others mentioned, there is no any direct system call to do the job. Instead,

  1. 您可以在发送带有TCP_INFO选项的数据包后检查我们是否收到了ACK.
  2. 如果我们没有收到 ACK,请等待几毫秒并再次检查.
  1. You can check if we have received the ACK after sending a packet with TCP_INFO option.
  2. If we haven't received the ACK, wait for few milliseconds and check again.

这可能会一直持续到超时.您必须将其实现为 send() 调用的包装函数.您将需要来自 <netinet/tcp.h>tcp_info 结构.它是保存您的tcp 连接信息的数据结构.

This may continue until a time out reaches. You have to implement it as a wrapper function to send() call. You will need tcp_info struct from <netinet/tcp.h>. It is the data structure for holding information about your tcp connection.

这是伪代码

int blockingSend(const char *msg, int msglen, int timeout) {

    std::lock_guard<std::mutex> lock(write_mutx);

    int sent = send(sock_fd, msg, msglen,  0); 

    tcp_info info;
    auto expireAt = chrono::system_clock::now() + chrono::milliseconds(timeout);
    do {
        this_thread::sleep_for(milliseconds(50));
        getsockopt(sock_fd,SOL_TCP, TCP_INFO, (void *) &info, sizeof(info));

      //wait till all packets acknowledged or time expires
    } while (info.tcpi_unacked > 0 && expireAt > system_clock::now());

    if(info.tcpi_unacked>0) {
        cerr << "no of unacked packets :" << info.tcpi_unacked << endl;
        return -1;
    }
    return sent;
}

这里的tcpi_unacked 成员保存了您的连接未确认 的数据包数.如果您在 send() 调用后不久阅读它,它将包含 unacked 数据包的数量,该数量等于发送的数据包数量.随着时间的推移,未确认数据包的数量将减少到零.因此,您需要定期检查 tcpi_unacked 的值,直到它达到零.如果连接半开,您将永远不会收到 ACKs 并导致无限循环.对于这种情况,您可能需要添加如上实现的 timeout 机制.

Here tcpi_unacked member holds the number of packets unacknowledged of your connection. If you read it soon after the send() call, it will contain number of unacked packets which is equal to number of packets sent. With time, number of unacked packets will be decremented to zero. Therefore you need to periodically check the value of tcpi_unacked till it reaches zero. If the connection is half opened, you will never receive ACKs while causing a endless loop. For such scenarios you may need to add a timeout mechanism as implemented above.

尽管这个问题很久以前就被问过了,但这个答案可能会对遇到同样问题的人有所帮助.我必须提到,这个问题可能有比这个解决方案更准确的解决方案.由于我是系统编程和 C/C++ 的新手,这就是我能想到的.

这篇关于有没有办法阻止套接字发送(),直到我们得到该数据包的确认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆