如何为不同的线程找到并保留可用端口?
我正在尝试构建两个通过 UDP 套接字进行通信的组件。组件 1 位于主线程中,组件 2 位于辅助线程中。该应用程序的多个副本可以同时在同一台计算机上运行,因此我无法使用固定端口。该程序还需要在 Windows 和 Linux 上运行。
我一直在尝试通过绑定 2 个 QUdpSockets 将端口指定为 0 (要求 Qt 为我选择一个空闲端口)来做到这一点。然后,我将第一个 QUdpSocket 和第二个套接字的参数传递给组件 1,为其提供发送和接收所需的一切。对于组件 2,我认为我无法跨线程边界传递 QUdpSocket,因此我仅传递参数并在辅助线程中构造+绑定套接字。
但是,辅助线程中的套接字绑定失败。大概是因为主线程中已经有套接字绑定到同一端口。
有什么方法可以解决这个问题,同时在构造任一对象之前仍然知道两个端口?
I'm trying to construct two components that communicate via UDP sockets. Component 1 is in the main thread and Component 2 is in a secondary thread. Multiple copies of this application can be running on the same machine at the same time, so I can't used fixed ports. The program also needs to be run on both Windows and Linux.
I've been trying to do this by binding 2 QUdpSockets specifying the port as 0 (asking Qt to choose a free port for me). I then pass the first QUdpSocket and the second socket's parameters to component 1, giving it all it needs to send and receive. For Component 2, I don't think I can pass the QUdpSocket across the thread boundary, so I pass only parameters and construct + bind the socket in the secondary thread.
However, the binding of the socket in the secondary thread fails. Presumably because there's already the socket in the main thread bound to the same port.
Is there any way I can resolve this while still knowing both ports prior to constructing either object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以,所以就这样做。只是不要同时在两个线程中使用它。
You can, so do that. Just don't use it in both your threads simultaneously .