【问题标题】:Rebind using new QUdpSocket使用新的 QUdpSocket 重新绑定
【发布时间】:2011-06-09 05:46:21
【问题描述】:

我有一个使用 UDP 广播进行设备发现的网络应用程序,但一次只接受一个连接。因此,当建立新的 TCP 连接时,我删除了用于发现的 QUdpSocket。

但是,当远程设备断开连接时,我想创建一个新的 QUdpSocket 并重新开始监听:

    // Set up a UDP server to respond to any "discovery" messages:
    udpServer = new QUdpSocket(this);
    if (udpServer -> bind(QHostAddress::Any, DISCOVERY_PORT))
        connect(udpServer, SIGNAL(readyRead()),
                this,      SLOT(beDiscovered()));
    else
    {
        fprintf(stderr, "UDP port not bound successfully: %d, ", udpServer ->error());
        fprintf(stderr, udpServer ->errorString().toLocal8Bit());
        fprintf(stderr, "\r\n");
        fflush(stderr);
#ifdef WIN32
        _commit(_fileno(stderr));
#else
        fsync(_fileno(stderr));
#endif
    }

但是,重新绑定失败,代码为 8,“绑定地址已在使用中”。

那么,我如何确保当“旧”QUdpSocket 被删除时,它会完全释放它所绑定的地址?

另外,我应该绑定 QUdpSocket::ShareAddress 还是 QUdpSocket::ReuseAddressHint?这似乎不对,因为两者都没有真正描述我想要的行为,即我的 QUdpSocket 在其生命周期内的独占绑定,并且无论如何 QUdpSocket::ShareAddress 应该是 Windows 上的默认值。

谢谢, 斯蒂芬。

【问题讨论】:

  • 我刚刚注意到一些事情。上面引用的代码在 Qt“槽”内。当远程主机断开连接时,插槽会被快速连续调用两次。第一次看起来 UdpSocket 设置正确,所以第二次它使用相同的指针创建另一个新的 QUdpSocket 并发现它无法绑定它——这不足为奇。
  • 将上述代码包含在“if (!udpServer)”块中可以暂时解决问题,但我想我现在需要找到导致调用插槽的虚假信号的来源什么时候不应该。

标签: qt data-binding udp


【解决方案1】:

...换句话说,问题已经自己回答了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 2012-09-21
    • 1970-01-01
    • 2015-01-26
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多