Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent send and receive data in one port with udpclient

Tags:

c#

udp

I'm trying to send and receive data to a specific endpoint with local port 50177. Send data does very good, but when the program tries to receive data it can't receive any. When I sniff the network with Wireshark I see that server sent data to me. I know that I can't have 2 UdpClient on one port at the same time.

Can any one help me?

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);
like image 667
Koorosh Sarfaraz Avatar asked Nov 29 '11 16:11

Koorosh Sarfaraz


2 Answers

You can absolutely have two UdpClient on one port but you need to set socket options before you bind it to an endpoint.

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);
}
like image 161
Farzan Avatar answered Sep 19 '22 22:09

Farzan


Use the same IPEndPoint for receiving that you used for sending.

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);
like image 31
jasonp Avatar answered Sep 20 '22 22:09

jasonp