今天小试了一下在Asp.net core中使用websocket,这里记录一下:
app.UseWebSockets();
它也可以传入一些参数
app.UseWebSockets(new WebSocketOptions(){KeepAliveInterval = TimeSpan.FromSeconds(120),ReceiveBufferSize = 4 * 1024});
async Task WebSocketMiddleware(HttpContext context, Func<Task> next){//这里监听的是 /ws 作为地址if (context.Request.Path != "/ws"){await next();return;}if (!context.WebSockets.IsWebSocketRequest){context.Response.StatusCode = 400;return;}WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();await Echo(context, webSocket);}
app.Use(WebSocketMiddleware);
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);}
到此一个简单的websocket应用就完成了,我们可以随便找一个测试webscoket的程序或在线网页测试一下了。
最后需要说明一下的时,本身asp.net core的websocket是可以在win7下跑的(来自于Kestrel内核的支持),但win7下的iis是不支持websocket反向代理的,因此如果在win7下开发或测试的时候,不要用iis来反向代理asp.net core程序。