码迷,mamicode.com
首页 > Web开发 > 详细

WebSocket简单使用

时间:2019-11-09 13:25:28      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:span   color   request   rsize   建立   etop   line   send   empty   

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

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与客户端建立连接名相同即可

 

 

 

 

 

 

 

WebSocket简单使用

标签:span   color   request   rsize   建立   etop   line   send   empty   

原文地址:https://www.cnblogs.com/fangyyy/p/11824969.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!