protected async Task InvokeWSAsync(HttpContext context, WSUserInfo userInfo, ConnectionAborted abortStatus = ConnectionAborted.None) { try { await WebSocketHub.WSManager.RemoveWebSocketIfExists(userInfo.Id); var socket = await context.WebSockets.AcceptWebSocketAsync(); if (abortStatus == ConnectionAborted.None) { await WebSocketHub.OnConnectedAsync(socket, userInfo); await Receive(socket, async (result, buffer) => { if (result.MessageType == WebSocketMessageType.Binary) { await WebSocketHub.ReceiveMessageAsync(socket, Encoding.UTF8.GetString(buffer, 0, result.Count)); } else { await WebSocketHub.OnDisconnectedAsync(userInfo.Id); } return; }); } else { await WebSocketHub.WSManager.AbortConnection(socket, abortStatus); } } catch { throw; } }
private async Task Receive(System.Net.WebSockets.WebSocket socket, Action <WebSocketReceiveResult, byte[]> handleMessage) { try { var buffer = new byte[WebSocketManager.WebSocketBufferSize]; while (socket.State == WebSocketState.Open) { var result = await socket.ReceiveAsync(buffer : new ArraySegment <byte>(buffer), cancellationToken : CancellationToken.None); handleMessage(result, buffer); } } catch { await WebSocketHub.OnDisconnectedAsync(WebSocketHub.WSManager?.GetId(socket)); } }
public WebSocketRESTfulMiddleware(RequestDelegate next, WebSocketHub webSocketHub, ILogger <WebSocketRESTfulMiddleware> logger) { WebSocketHub = webSocketHub; Logger = logger; }