C#BeginReceive for UDP

时间:2013-07-11 08:02:32

标签: c# .net udp udpclient

我正在尝试学习如何使用BeginReceive for UDP,这就是我所拥有的:

        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);

    }

没有任何反应,代码只是在没有调用recv方法的情况下结束。那是为什么?

修改

补充: -

   Console.ReadLine();

现在它在下面一行给我一个例外:

 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);

        }

错误:

'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?)

1 个答案:

答案 0 :(得分:2)

如果代码的第一部分基本上是主函数的主体,那么结束时不应该感到惊讶。放一个

Console.Readline();
}的结束main等待之前

一旦数据到达,

recv将被异步调用。然后,您需要从正在等待的UDP客户端读取接收的数据。要访问此客户端,您可以通过BeginReceive

的状态参数将其交给您
client.BeginReceive(new AsyncCallback(recv), client);

最后从回调IAsyncResult参数中获取它

UdpClient client = (UdpClient)res.AsyncState;

将客户端存储在类字段中可能更容易(但不太灵活)。

现在您可以从

获取数据
byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);