1. 程式人生 > >在.net core web網站中新增webSocket支援

在.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);

}