zoukankan      html  css  js  c++  java
  • 在.net core web网站中添加webSocket支持

    注意:前置条件,操作系统 windows 8 以上,IIS Express 8.0 以上.

     

    第1步:在Startup.cs文件的头部添加如下引用:

    using System.Net.WebSockets;

    using System.Threading;

    using System.Threading.Tasks;

     

    第2步:在Startup.cs文件的Configure方法中增加以下代码

    #region WebSocket

    var webSocketOptions = new WebSocketOptions()

    {

        KeepAliveInterval = TimeSpan.FromSeconds(120),

        ReceiveBufferSize = 4 * 1024,

    };

     

    app.UseWebSockets(webSocketOptions);

     

    app.Use(async (context, next) =>

    {

        if (context.Request.Path == "/ws")

        {

            if (context.WebSockets.IsWebSocketRequest)

            {

                WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                await Echo(context, webSocket);

            }

            else

            {

                context.Response.StatusCode = 400;

                await next();

            }

        }

        else

        {

            await next();

        }

    });

    #endregion

    第3步:在Startup.cs文件中增加Echo方法。

    代码如下:

    private async Task Echo(HttpContext context, WebSocket webSocket)

    {

    var buffer = new byte[1024 * 4];

    WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

    while (!result.CloseStatus.HasValue)

    {

        await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);

        result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

      }

      await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);

    }

  • 相关阅读:
    Centos6.8部署jumpserver(完整版)
    Linux系统下inode满了导致无法写文件的解决思路
    MySQL5.7.20报错Access denied for user 'root'@'localhost' (using password: NO)
    深浅拷贝
    集合
    列表 元组 range
    机器码和字节码
    函数
    文件操作
    小数据池和代码块
  • 原文地址:https://www.cnblogs.com/tshaoguo/p/10154977.html
Copyright © 2011-2022 走看看