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

  • 相关阅读:
    PorterDuff及Xfermode初识
    Android内存优化之——static使用篇
    Realm for Android快速入门教程
    Android 你应该知道的学习资源 进阶之路贵在坚持
    Google 发布 Android 性能优化典范
    Android Studio 打包及引用 aar
    Android CoordinatorLayout + AppBarLayout(向上滚动隐藏指定的View)
    elevation 和 translationZ的区别
    rsync+inotify实时数据同步多目录实战
    rsync+inotify实时数据同步单目录实战
  • 原文地址:https://www.cnblogs.com/hedongnan/p/3143022.html
Copyright © 2011-2022 走看看