首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UDP的C# BeginReceive

UDP的C# BeginReceive
EN

Stack Overflow用户
提问于 2013-07-11 08:02:31
回答 1查看 6.5K关注 0票数 0

我正在努力学习如何将BeginReceive用于UDP,下面是我所拥有的:

代码语言:javascript
复制
        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方法。那是为什么?

编辑

加:-

代码语言:javascript
复制
   Console.ReadLine();

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

代码语言:javascript
复制
 Only one usage of each socket address is normally permitted. 

试过:-

代码语言:javascript
复制
       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);

        }

错误:

代码语言:javascript
复制
'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?)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-11 08:09:13

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

代码语言:javascript
复制
Console.Readline();

在关闭} of main之前等待。

一旦一些数据到达,recv将被异步调用。然后,您需要从等待的UDP客户端读取接收的数据。为了访问这个客户机,您将通过BeginReceive的状态参数传递它

代码语言:javascript
复制
client.BeginReceive(new AsyncCallback(recv), client);

并最终从回调IAsyncResult参数获得它。

代码语言:javascript
复制
UdpClient client = (UdpClient)res.AsyncState;

在类字段中存储客户机可能更容易(但不那么灵活)。

现在您可以从

代码语言:javascript
复制
byte[] received = client.EndReceive(res, ref RemoteIpEndPoint);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17588099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档