zoukankan      html  css  js  c++  java
  • udpclient之异步编程

      首先,自定义一个类,这了类之后会用到。

    class UdpState
        {
            public UdpClient u;
            public IPEndPoint e;
        }

    以下是主要代码,虽然是用udpclient来编程,但是这是编写的Server端代码,主要用到了异步接收方发,具体的方法讲解可以在MSDN上查看:

            public static void ReceiveCallback(IAsyncResult ar)
            {
                UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
                IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

                Byte[] receiveBytes = u.EndReceive(ar, ref e);
                string receiveString = Encoding.ASCII.GetString(receiveBytes);

                Console.WriteLine("Received: {0}", receiveString);
                messageReceived = true;
            }

            public static void ReceiveMessages()
            {
                  int listenPort=11000;
                // Receive a message and write it to the console.
                IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
                UdpClient u = new UdpClient(e);

                UdpState s = new UdpState();//此处用到了自定义的类
                s.e = e;
                s.u = u;

                Console.WriteLine("listening for messages");
                u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

                // Do some work while we wait for a message. For this example,
                // we'll just sleep
                while (!messageReceived)
                {
                    Thread.Sleep(10000);
                }
            }

  • 相关阅读:
    二分查找 java代码
    Failed at the bitcore-node@3.1.3 preinstall script './scripts/download' 设置linux proxy (代理)的方式
    github命令行实用操作
    H5无障碍旁白模式使用网页支持
    Vue框架搭建入门到熟悉
    解决IOS下返回不刷新的问题
    小程序—跳转 数据传递
    微信小程序——地图
    常用的正则判断
    JS 控制输入框输入表情emoji 显示在页面上
  • 原文地址:https://www.cnblogs.com/hedongnan/p/3143022.html
Copyright © 2011-2022 走看看