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

  • 相关阅读:
    css居中问题(转)
    Request.ServerVariables 各个参数的用法
    html5 画个球碰撞
    递归生成json
    AspNetPager分页结合存储过程的用法
    sql+aspnetpager+查询功能
    求1+2+……+n
    几种排序的比较 bitmapsort,qsort,set
    利用两个栈,反转其中一个栈的元素
    进程间通信(IPC, Inter Process Communication)读书笔记
  • 原文地址:https://www.cnblogs.com/hedongnan/p/3143022.html
Copyright © 2011-2022 走看看