使用udpclient在一个端口中并发发送和接收数据

时间:2011-11-29 16:24:42

标签: c# udp

我尝试使用本地端口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);

2 个答案:

答案 0 :(得分:7)

在一个端口上绝对可以有两个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);
}

答案 1 :(得分:1)

使用相同的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);