• 测试HttpListener监听请求----处理WebSocketRequest


    测试HttpListener监听请求,代码如下:

    #region 测试HttpListenerWebSocket
    
            /// <summary>
            /// 测试HttpListener
            /// </summary>
            public static async void TestHttpListenerWebSocket()
            {
                var threadStart = new Thread(new ThreadStart(StartHttpListenerWebSocket))
                {
                    IsBackground = true
                };
                threadStart.Start();
                Console.WriteLine($"WebSocket开始测试数据");
    
                int test = 1;
                while (true)
                {
                    ClientWebSocket clientWebSocket = new ClientWebSocket();
                    await clientWebSocket.ConnectAsync(new Uri("ws://localhost:5566"), default);
                    if (clientWebSocket.State == WebSocketState.Open)
                    {
                        var bytes = Encoding.UTF8.GetBytes($"客户端发---{test}");
                        var bufferSend = new ArraySegment<byte>(bytes);
                        await clientWebSocket.SendAsync(bufferSend, WebSocketMessageType.Text, true, default);
    
                        var buffer = new byte[1024];
                        var webSocketReceiveResult = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), default);
                        var result = Encoding.UTF8.GetString(buffer, 0, webSocketReceiveResult.Count);
                        Console.WriteLine($"客户端收---{result}");
                    }
                    test++;
                    Thread.Sleep(1000);
                }
            }
    
            public static async void StartHttpListenerWebSocket()
            {
                HttpListener httpListener = new HttpListener();
                //httpListener.Prefixes.Add("http://localhost:5566/");
                //httpListener.Prefixes.Add("http://+:5566/");
                httpListener.Prefixes.Add("http://*:5566/");
                httpListener.Start();
                Console.WriteLine($"httpListener 启动监听");
                while (true)
                {
                    //var asyncResult = httpListener.BeginGetContext(new AsyncCallback(CallbackWebSocket), httpListener);
                    //asyncResult.AsyncWaitHandle.WaitOne();
                    //下面也可以
                    //var httpListenerContext = httpListener.GetContextAsync().GetAwaiter().GetResult();
                    //var httpListenerContext = httpListener.GetContextAsync().Result;
                    var httpListenerContext = await httpListener.GetContextAsync();
                    //处理httpListenerContext
                    ProcessHttpListenerContextWebSocket(httpListenerContext);
                }
            }
    
            private static async void ProcessHttpListenerContextWebSocket(HttpListenerContext httpcontent)
            {
                if (httpcontent.Request.IsWebSocketRequest)//处理WebSocketRequest
                {
                    var webSocketContext = await httpcontent.AcceptWebSocketAsync(null);
                    var webSocket = webSocketContext.WebSocket;
                    var buffer = new byte[1024];
                    var WebSocketReceiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), default);
                    var result = Encoding.UTF8.GetString(buffer, 0, WebSocketReceiveResult.Count);
                    Console.WriteLine($"服务端 收到:{result}");
    
                    var bytes = Encoding.UTF8.GetBytes($"服务端处理:{result}");
                    var bufferSend = new ArraySegment<byte>(bytes);
                    await webSocket.SendAsync(bufferSend, WebSocketMessageType.Text, true, default);
                    webSocket.Dispose();
                }
                else //处理HttpWebRequest
                {
                    Console.WriteLine($"HttpWebRequest 请求");
                    if (httpcontent.Request.HttpMethod == HttpMethod.Post.ToString())
                    {
                        Console.WriteLine($"请求方法:{httpcontent.Request.HttpMethod}");
                        var input = new StreamReader(httpcontent.Request.InputStream).ReadToEnd();
                        var bytes = Encoding.UTF8.GetBytes($"我们收到数据:{input},哈哈哈哈");
                        httpcontent.Response.OutputStream.Write(bytes, 0, bytes.Length);
                        httpcontent.Response.Close();
                    }
                    else
                    {
                        Console.WriteLine($"请求方法:{httpcontent.Request.HttpMethod}");
                        var bytes = Encoding.UTF8.GetBytes($"{httpcontent.Request.RawUrl}----哈哈哈哈");
                        httpcontent.Response.OutputStream.Write(bytes, 0, bytes.Length);
                        httpcontent.Response.Close();
                    }
                }
            }
    
            private static async void CallbackWebSocket(IAsyncResult ar)
            {
                var httplist = (HttpListener)ar.AsyncState;
                var httpcontent = httplist.EndGetContext(ar);
                if (httpcontent.Request.IsWebSocketRequest)
                {
                    var webSocketContext = await httpcontent.AcceptWebSocketAsync(null);
                    var webSocket = webSocketContext.WebSocket;
                    var buffer = new byte[1024];
                    await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), default);
                    var result = Encoding.UTF8.GetString(buffer.ToArray());
                    var bytes = Encoding.UTF8.GetBytes($"我们收到数据:{result},以处理");
                    var bufferSend = new ArraySegment<byte>(bytes);
                    await webSocket.SendAsync(bufferSend, WebSocketMessageType.Text, true, default);
                }
            }
    
            #endregion

    测试结果如下:

     public class Program
        {
            static void Main(string[] args)
            {
                #region  #region 测试TestHttpListener
                TestHttpListenerWebSocket();
                #endregion
                Console.Read();
            }
        }

  • 相关阅读:
    jq 获取下一个兄弟原素 下拉箭头旋转
    weui复选框无法传值
    小乌龟 coding 克隆、提交一直提示无权限
    mysql 时间操作
    Mysql表结构导出excel(含数据类型、字段备注注释)
    sql server数据库文件的迁移(mdf&ldf文件)
    thinkphp 5 _initialize 使用问题
    thinkphp5 or
    找实习与校招总结——经验与收获2021
    千兆网数据CRC检验和过滤
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/14150022.html
Copyright © 2020-2023  润新知