我正在使用以下代码从udp套接字读取,该代码运行良好。现在我需要将recv中的'received'传递给调用main。怎么办呢。
try
{
client.BeginReceive(new AsyncCallback(recv), client);
}
private static void recv(IAsyncResult res)
{
try
{
UdpClient c = (UdpClient)(res.AsyncState);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 162);
byte[] received = c.EndReceive(res, ref RemoteIpEndPoint);
Console.WriteLine(ASCIIEncoding.ASCII.GetString(received));
c.BeginReceive(new AsyncCallback(recv), c);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
答案 0 :(得分:1)
在.Net 4.5中,您可以像这样使用async/await
:
using (var udpClient = new UdpClient())
{
try
{
udpClient.Connect(IPAddress.Any, 162);
UdpReceiveResult receiveAsync = await udpClient.ReceiveAsync();
Console.WriteLine(Encoding.ASCII.GetString(receiveAsync.Buffer));
}
catch (Exception e)
{
Console.WriteLine(e);
}
}