tags:

views:

75

answers:

0

Tried to implement a very basic udp agent in c#, that echos back whatever is sent to it, but obviously I'm doing it wrong. The server crashes when calling BeginReceive for the second time ("re-listening to the socket") with

Unhandled Exception: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.DoBeginReceiveFrom(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint endPointSnapshot, SocketAddress socketAddress, OverlappedAsyncResult asyncResult)

The circumstances leading to that exception are:

  1. The udp client on the other end terminates.
  2. The udp server tries to echo it back
  3. The client machine replies with an ICMP Port unreachable message
  4. The server thinks the connection was aborted, though I'm just trying to listen on a port without any specific remote end point.

The true question, I guess, is how to make a simple udp echo server that keeps on listening to incoming packets.

Here's my current implementation:

private static void OnReceive(IAsyncResult ar)
{
  UdpClient udpClient = (UdpClient)(ar.AsyncState);
  try
  {
    IPEndPoint e = new IPEndPoint(IPAddress.Any, 0);
    Byte[] receiveBytes = udpClient.EndReceive(ar, ref e);
    string s = System.Text.ASCIIEncoding.ASCII.GetString(receiveBytes);
    Console.WriteLine(s);
    udpClient.Send(receiveBytes, receiveBytes.Length, e);
  }
  catch (Exception e)
  {
  }
  udpClient.BeginReceive(OnReceive, udpClient);
}

public static void Main(string[] args)
{
  UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.1.43"), 42));
  client.BeginReceive(OnReceive, client);
  Console.WriteLine("Press enter to exit");
  Console.ReadLine();
}

Thanks for your replies!

EDIT: I can do something like the following, is that correct?

  try
  {
    udpClient.BeginReceive(OnReceive, udpClient);
  }
  catch (Exception e)
  {
    udpClient.Close();
    udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.1.43"), 42));
    udpClient.BeginReceive(OnReceive, udpClient);
  }