我正在尝试使用本地端口50177向特定端点发送和接收数据.发送数据非常好,但是当程序尝试接收数据时,它无法接收任何数据.当我用Wireshark嗅探网络时,我看到服务器向我发送了数据.我知道我不能同时在一个端口上安装2个UdpClient.
谁能帮我?
UdpClient udpClient2 = new UdpClient(50177);
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005);
udpClient2.Send(peerto255, peerto255.Length, Ip2);
IPEndPoint Ip = new IPEndPoint(IPAddress.Parse("10.10.240.1"), 1005);
var dgram = udpClient2.Receive(ref Ip);
Run Code Online (Sandbox Code Playgroud)
在一个端口上绝对可以有两个UdpClient,但是在将它绑定到端点之前需要设置套接字选项.
private static void SendAndReceive()
{
IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, 1234);
ThreadPool.QueueUserWorkItem(delegate
{
UdpClient receiveClient = new UdpClient();
receiveClient.ExclusiveAddressUse = false;
receiveClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiveClient.Client.Bind(ep1);
byte[] buffer = receiveClient.Receive(ref ep1);
});
UdpClient sendClient = new UdpClient();
sendClient.ExclusiveAddressUse = false;
sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint ep2 = new IPEndPoint(IPAddress.Parse("X.Y.Z.W"), 1234);
sendClient.Client.Bind(ep1);
sendClient.Send(new byte[] { ... }, sizeOfBuffer, ep2);
}
Run Code Online (Sandbox Code Playgroud)
使用与发送相同的 IPEndPoint 进行接收。
UdpClient udpClient2 = new UdpClient(50177);
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005);
udpClient2.Send(peerto255, peerto255.Length, Ip2);
var dgram = udpClient2.Receive(ref Ip2);
Run Code Online (Sandbox Code Playgroud)