在.net core web网站中添加webSocket支持
2018-12-21 11:57 tshaoguo 阅读(1561) 评论(0) 编辑 收藏 举报注意:前置条件,操作系统 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);
}