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

  • 相关阅读:
    fescar源码解析系列(一)之启动详解
    dubbo源码解析二 invoker链
    dubbo源码解析一
    CSP-S 2021 游记
    使用SpEL记录操作日志的详细信息
    Router 重定向和别名是什么?
    vue项目做seo(prerender-spa-plugin预渲染)
    vue3.0初体验有哪些实用新功能
    uniapp弹窗踩坑
    Spring boot application.properties 配置
  • 原文地址:https://www.cnblogs.com/hedongnan/p/3143022.html
Copyright © 2011-2022 走看看