且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

让两个 UDP 服务器监听同一个端口?

更新时间:2023-11-22 19:19:52

这个答案参考了 cdhowie 的答案,他链接了一个文档,该文档指出 SO_REUSEPORT 会产生我想要达到的效果.

This answer is referenced to the answer of cdhowie, who linked a document which states that SO_REUSEPORT would have the effect I'm trying to achieve.

我研究了如何以及是否实施此选项,并主要关注 Boost::Asio 和 Linux.

I've researched how and if this option is implemented and focused mainly on Boost::Asio and Linux.

Boost::Asio 仅在操作系统等于 BSD 或 MacOSX 时才设置此选项.该代码包含在文件 boost/asio/detail/reactive_socket_service.hpp 中(Boost 版本 1.40,在较新的版本中,代码已移至其他文件中).
我想知道为什么 Asio 没有为 Linux 和 Windows 等平台定义这个选项.

Boost::Asio does only set this option if the OS is equal to BSD or MacOSX. The code for that is contained in the file boost/asio/detail/reactive_socket_service.hpp (Boost Version 1.40, in newer versions, the code has been moved into other files).
I've wondered why Asio does not define this option for platforms like Linux and Windows.

有几个参考资料讨论了这在 Linux 中没有实现:https://web.archive.org/web/20120315052906/http://kerneltrap.org/mailarchive/linux-netdev/2008/8/7/2851754
http://kerneltrap.org/mailarchive/linux-kernel/2010/6/23/4586155

There are several references discussing that this is not implemented in Linux: https://web.archive.org/web/20120315052906/http://kerneltrap.org/mailarchive/linux-netdev/2008/8/7/2851754
http://kerneltrap.org/mailarchive/linux-kernel/2010/6/23/4586155

还有一个补丁可以将此功能添加到内核中:https://web-beta.archive.org/web/20110807043058/http://kerneltrap.org/mailarchive/linux-netdev/2010/4/19/6274993

There also is a patch which should add this functionality to the kernel: https://web-beta.archive.org/web/20110807043058/http://kerneltrap.org/mailarchive/linux-netdev/2010/4/19/6274993

我不知道 Windows 是否存在此选项,但是通过将 portable 定义为同样在 Linux 上运行的软件的属性,这意味着 SO_REUSEPORT 是特定于操作系统的,并且没有我的问题的便携式解决方案.

I don't know if this option is existing for Windows, but by defining portable as an attribute for software which runs on Linux too, this means, that SO_REUSEPORT is OS specific and there is no portable solution for my question.

在我链接的其中一个讨论中,建议 UDP 实现一个主侦听器,然后将传入的数据提供给多个从属侦听器.

In one of the discussions I've linked it is recommended for UDP to implement a master-listener which then provides the incoming data to multiple slave-listeners.

我会将这个答案标记为已接受(尽管接受我自己的答案感觉有点糟糕),因为它指出了为什么使用 SO_REUSEPORT 的方法在尝试与便携式软件一起使用时会失败.

I will mark this answer as accepted (though feeling kind of bad by accepting my own answer), because it points out why the approach of using SO_REUSEPORT will fail when trying to use it with portable software.