如何在 ASP.NET Core RC2 中制作 websocket 服务器?

How to make websocket server in ASP.NET Core RC2?

我使用 "Microsoft.AspNetCore.WebSockets.Server": "0.1.0-rc2-final" 制作了一个 websocket 服务器,但是没有用。 (在rc1中,它是1.0.0-rc1-final,而且工作正常...)

这是我的代码:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseWebSockets();

        app.Use(async (http, next) =>
        {

            if (http.WebSockets.IsWebSocketRequest)
            {
                IHandler handler = WebsocketManager.getHandler(http.Request.Path);
                if (handler == null)
                {
                    await next();
                }
                else
                {
                    var webSocket = await http.WebSockets.AcceptWebSocketAsync();
                    if (webSocket != null && webSocket.State == WebSocketState.Open)
                    {
                        // TODO: Handle the socket here.
                        WebsocketManager.Handle(webSocket, handler);
                    }
                }
            }
            else
            {
                // Nothing to do here, pass downstream.  
                await next();
            }
        });


        app.UseMvc();
    }

WebsocketManager 是我自己的管理器class。 这是我处理 websocket 会话的方式:

    public async Task Listen()
    {
        OnOpen();
        while (_webSocket.State == WebSocketState.Open)
        {
            var error = String.Empty;

            try
            {
                var buffer = new ArraySegment<Byte>(new Byte[4096]);
                var received = await _webSocket.ReceiveAsync(buffer, CancellationToken.None);

                switch (received.MessageType)
                {
                    case WebSocketMessageType.Close:
                        OnClose(received.CloseStatus, received.CloseStatusDescription);
                        break;
                    case WebSocketMessageType.Text:
                        var data = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count).Trim('[=12=]');
                        OnMessage(data);
                        break;
                    case WebSocketMessageType.Binary:
                        OnMessage(buffer.Array);
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                break;
            }
        }
    }

然后,“_webSocket.ReceiveAsync”抛出异常"The request was aborted."

我确定客户端不会关闭会话。

如何解决?

您需要await这一行: WebsocketManager.Handle(webSocket, handler); 否则请求结束,资源被释放。