Joel
Joel

Reputation: 587

Using C# UDP Client

I'm making a program which needs to be listening for UDP Data at all times.

My current idea is have this method running constantly in one thread listening for packets and then adding them to a list ready to be dealt with in other threads. The main problem is I would also like to add the received IP to a list so that the other thread can deal with it but I don't know if the program stops using the Receive method for a moment if it will lose packets received while processing the data or if it can still grab them from a queue.

public void listen()
{
    try
    {
        packetQueue.Add(receivingUdpClient.Receive(ref RemoteIpEndPoint)); 
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

Upvotes: 1

Views: 645

Answers (2)

mtijn
mtijn

Reputation: 3678

network traffic should be buffered on your network card so the data should be consistent even if you are listening inconsistently. as for the IP you can get it from the endpoint so you'll need to pass that as well:

public void listen()
  {
      try
      {
          packetQueue.Add(receivingUdpClient.Receive(ref RemoteIpEndPoint), RemoteIpEndPoint);
       }
      catch (Exception e)
      {
          Console.WriteLine(e.ToString());
      }
  }

If you want to miss as little time as possible in between receives I suggest you use BeginReceive and start a new BeginReceive in the callback before processing the received data in the callback. this will add some synchronization complexity though.

Upvotes: 1

DanTheMan
DanTheMan

Reputation: 3277

I know of no way to get the IP from the Udp packet. You need to get it form the EndPoint:

 byte[] receivedBytes = oClientListener.Receive(ref endPoint);
 IPAddress = endPoint.Address;
 PackQueue.Add( new PacketOfSomeType( receivedBytes, IPAdress ) );

Also, your program will need to run VERY SLOWLY to start losing any packets - windows will buffer those for you, so long as you have your client listener set up!

Upvotes: 1

Related Questions