使用新的 QUdpSocket 重新绑定

发布于 2024-10-12 05:16:01 字数 1041 浏览 1 评论 0原文

我有一个网络应用程序,它使用 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 上的默认设置。

谢谢, 史蒂芬.

I have a network application which uses UDP broadcasts for device discovery, but only accepts one connection at a time. So, when a new TCP connection is made, I delete the QUdpSocket that was used for discovery.

However, when the remote device is disconnected, I want to create a new QUdpSocket and start listening again:

    // 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
    }

The re-bind fails, however, with code 8, "The bound address is already in use".

So, how can I make sure that when the 'old' QUdpSocket was deleted, it fully releases the address(es) it was bound to?

Alternatievly, should I be binding with QUdpSocket::ShareAddress or QUdpSocket::ReuseAddressHint? This doesn't seem right, as neither really describe the behaviour I want, namely an exclusive binding for my QUdpSocket during its lifetime, and in any case QUdpSocket::ShareAddress is supposed to be the default on Windows.

Thanks,
Stephen.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狂之美人 2024-10-19 05:16:01

……换句话说,问题已经有了答案!

...so in other words the question has answered itself!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文