Beginreceive / Endreceive传递参数

时间:2013-07-11 11:03:15

标签: c# .net udpclient

我正在使用以下代码从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);

        }
    }

1 个答案:

答案 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);
    }
}