0

私はUDPにBeginReceiveを使用する方法を学ぼうとしています.これが私が持っているものです:

        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

コードの最初の部分が本質的にメイン関数の本体である場合、それが終了しても驚かないでください。置く

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 に答える