UdpClient.BeginReceive callback function??

T

Tenacious

MSDN gives this code as an example to create a callback function for
UdpClient.BeginReceive. It doesn't compile because the compiler does
not recognize "UdpState". I can't find any info on it either. Does
anyone know what "UdpState" is or could you point me to some sample
code on how to properly implement a ReceiveCallback function? Any help
would be appreciated.

public static bool messageReceived = false;
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);

Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}

MSDN link:
ms-help://MS.MSDN.vAug06.en/cpref10/html/M_System_Net_Sockets_UdpClient_BeginReceive_1_2bb042b2.htm
 
P

Patrick Steele

MSDN gives this code as an example to create a callback function for
UdpClient.BeginReceive. It doesn't compile because the compiler does
not recognize "UdpState". I can't find any info on it either. Does
anyone know what "UdpState" is or could you point me to some sample
code on how to properly implement a ReceiveCallback function? Any help
would be appreciated.

public static bool messageReceived = false;
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

Byte[] receiveBytes = u.EndReceive(ar, ref e);
string receiveString = Encoding.ASCII.GetString(receiveBytes);

Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}

MSDN link:
ms-help://MS.MSDN.vAug06.en/cpref10/html/M_System_Net_Sockets_UdpClient_BeginReceive_1_2bb042b2.htm

Looks like they missed part of the code. My guess is that it's a simple
class to maintain some state in the Async call. Probably:

public class UdpState
{
public UdpClient u;
public IPEndPoint e;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top