Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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);
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 :-
client.BeginReceive(new AsyncCallback(recv), client);
private static void recv(IAsyncResult res)
// int port = 162;
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?)
–
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);
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.