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

2019-06-10 16:24发布

问题:

I use "Microsoft.AspNetCore.WebSockets.Server": "0.1.0-rc2-final" to make a websocket server, but not work. (In rc1, it is 1.0.0-rc1-final, and it work fine...)

Here is my code:

    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 is my own manager class. And Here is how I handle websocket session:

    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('\0');
                        OnMessage(data);
                        break;
                    case WebSocketMessageType.Binary:
                        OnMessage(buffer.Array);
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                break;
            }
        }
    }

And then, "_webSocket.ReceiveAsync" thrown exception "The request was aborted."

I am sure client not close the session.

How to fix it?

回答1:

You need to await this line: WebsocketManager.Handle(webSocket, handler); Otherwise the request ends and the resources get disposed.