• WebSocket简单使用


    很简单就不写太多介绍了,仅展示服务端代码!!

    ConfigureStartup方法中添加WebSockets中间件

    app.UseWebSockets();

    可以配置以下设置:

    KeepAliveInterval 多久发送一次“ ping”帧到客户端,以确保代理保持连接打开。默认值为两分钟。

    ReceiveBufferSize     用于接收数据的缓冲区的大小。高级用户可能需要根据数据大小更改此项以进行性能调整。默认值为4 KB。

    var webSocketOptions = new WebSocketOptions()
                {
                    KeepAliveInterval = TimeSpan.FromSeconds(120),
                    ReceiveBufferSize = 200 * 1024
                };
                app.UseWebSockets(webSocketOptions);

    增加一个socket帮助类库

    SocketHandler
     public class SocketHandler
        {
            public const int BufferSize = 4096;
            public string basestringjson = string.Empty;
    
            WebSocket socket;
    
            SocketHandler(WebSocket socket)
            {
                this.socket = socket;
            }
    
            async Task EchoLoop()
            {
                var buffer = new byte[BufferSize];
                //代码接收消息并立即发回相同的消息。 循环发送和接收消息,直到客户端关闭连接
                WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                while (!result.CloseStatus.HasValue)
                {
                    await socket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
    
                    result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                }
                await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            }
    
            static async Task Acceptor(HttpContext hc, Func<Task> n)
            {
                if (!hc.WebSockets.IsWebSocketRequest)
                    return;
    
                var socket = await hc.WebSockets.AcceptWebSocketAsync();//将请求转换为WebSocket
                var h = new SocketHandler(socket);
                await h.EchoLoop();
            }
    
            /// <summary>
            /// branches the request pipeline for this SocketHandler usage
            /// </summary>
            /// <param name="app"></param>
            public static void Map(IApplicationBuilder app)
            {
                app.UseWebSockets();
                app.Use(SocketHandler.Acceptor);
            }
        }

    最后在startup.cs中调用,最终代码:

    var webSocketOptions = new WebSocketOptions()
                {
                    KeepAliveInterval = TimeSpan.FromSeconds(120),
                    ReceiveBufferSize = 200 * 1024
                };
                app.UseWebSockets(webSocketOptions);
                app.Map("/socketname", SocketHandler.Map);
    socketname与客户端建立连接名相同即可
  • 相关阅读:
    【做题】提高组过关测试题1
    【做题】arc078_f-Mole and Abandoned Mine——状压dp
    【学习】Hall’s Marriage Theorem
    【做题】arc072_f-Dam——维护下凸包
    一文尽览近似最近邻搜索中的哈希与量化方法
    InsightFace源码以及pre-train模型以及使用
    无法解析的外部符号 jpeg_std_error
    威布尔weibull distribution
    中科院- 生物特征识别概述
    Face-Resources
  • 原文地址:https://www.cnblogs.com/fangyyy/p/11824969.html
Copyright © 2020-2023  润新知