如何 运行 客户端和服务器 UDP 侦听器在同一台机器上

How to run client and server UDP listeners on the same machine

客户端和服务器都在给定端口上发送和接收。在生产中,它们在不同的机器上,没有问题。在开发中,将它们 运行 放在同一台机器上会方便得多,并且无需部署以及设置和拆除远程调试会话。

我试过了

var uc = new UdpClient();
var ep = new IPEndPoint(address, port);
uc.ExclusiveAddressUse = false;
uc.Client.Bind(ep);

它不会 barf 但我仍然无法将多个侦听器绑定到同一端点。事实上,我发现 ExclusiveAddressUse 无论如何都默认为 false,所以这种方法只会产生额外的代码。

这可能吗?如果可能的话怎么办?

您显然不能在同一台机器上使用相同的端口,只需为 debug 使用 #if directive 并相应地更改您的端口

以下内容可能有帮助

客户端

#if DEBUG
    uc client = new UdpClient(34534);
#else
    uc client = new UdpClient();
#endif

UdpClient Constructor (Int32)

Initializes a new instance of the UdpClient class and binds it to the local port number provided.

备注

This constructor creates an underlying Socket and binds it to the port number from which you intend to communicate. Use this constructor if you are only interested in setting the local port number. The underlying service provider will assign the local IP address. If you pass 0 to the constructor, the underlying service provider will assign a port number. If this constructor is used, the UdpClient instance is set with an address family of IPv4 that cannot be changed or overwritten by a connect method call with an IPv6 target.

免责声明,完全未经测试,只是阅读文档,可能是错误的:)