Question

I'm trying to learn how to use BeginReceive for UDP, here's what I have:

        Console.WriteLine("Initializing SNMP Listener on Port:" + port + "...");
        UdpClient client = new UdpClient(port);
        //UdpState state = new UdpState(client, remoteSender);


        try
        {
          client.BeginReceive(new AsyncCallback(recv), null);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }


    }

    private static void recv(IAsyncResult res)
    {
        int port = 162;
        UdpClient client = new UdpClient(port);
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 162);
        byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
        Console.WriteLine(Encoding.UTF8.GetString(received));
        client.BeginReceive(new AsyncCallback(recv), null);

    }

Nothing happens, the code just end's without even calling the recv method. Why is that ?

Edit:

Added :-

   Console.ReadLine();

Now it's giving me an exception at the below line:

 Only one usage of each socket address is normally permitted. 

TRIED :-

       try
        {
          client.BeginReceive(new AsyncCallback(recv), client);
        }

    private static void recv(IAsyncResult res)
    {
    //    int port = 162;

        try
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 162);
            byte[] received = res.AsyncState.EndReceive(res, ref RemoteIpEndPoint);
            Console.WriteLine(Encoding.UTF8.GetString(received));
            res.AsyncState.BeginReceive(new AsyncCallback(recv), null);

        }

        catch (Exception e)
        {
            Console.WriteLine(e);

        }

Error:

'object' does not contain a definition for 'EndReceive' and no extension method 'EndReceive' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Was it helpful?

Solution

If the first part of your code is essentially the body of your main function you shouldn't be surprised that it ends. Put a

Console.Readline();

before the closing } of main to wait.

recv will be called asynchronously as soon as some data arrived. Then you need to read the received data from the very UDP client that was waiting. In order to access this client you'll hand it over via the state parameter of BeginReceive

client.BeginReceive(new AsyncCallback(recv), client);

and finally get it from the callbacks IAsyncResult parameter

UdpClient client = (UdpClient)res.AsyncState;

It may be easier (but less flexible) to store the client in a class field.

Now you get your data from

byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top