0

我正在尝试学习如何将 BeginReceive 用于 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. 

尝试过:-

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

1 回答 1

2

如果你的代码的第一部分本质上是你的 main 函数的主体,你不应该对它结束感到惊讶。放一个

Console.Readline();

收盘}main要等待。

recv一旦一些数据到达,将被异步调用。然后您需要从正在等待的 UDP 客户端读取接收到的数据。为了访问此客户端,您将通过 state 参数将其移交给BeginReceive

client.BeginReceive(new AsyncCallback(recv), client);

最后从回调 IAsyncResult 参数中获取

UdpClient client = (UdpClient)res.AsyncState;

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

现在您从

byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
于 2013-07-11T08:09:13.070 回答