public async void Dispatch(HttpListenerContext httpListenerContext) { // For health check requests, OK immediately if (httpListenerContext.Request.RawUrl.Equals("/health-check", StringComparison.InvariantCultureIgnoreCase)) { using (httpListenerContext.Response) { httpListenerContext.Response.StatusCode = 200; return; } } // For other requests, begin websocket upgrade WebSocketRemoteDevice remoteDevice = default; try { _logger.Trace($"{httpListenerContext.Request.RemoteEndPoint.Address}:{httpListenerContext.Request.RemoteEndPoint.Port} connected."); using (httpListenerContext.Response) { var webSocketContext = await httpListenerContext.AcceptWebSocketAsync(null); remoteDevice = new WebSocketRemoteDevice(new WebSocketClient(httpListenerContext, webSocketContext)); _logger.Trace($"{remoteDevice} Http -> WebSocket upgraded OK."); using (webSocketContext.WebSocket) { await _remoteDeviceConnectedHandler.HandleAsync(remoteDevice); } } } catch (IOException ex) { _logger.Warn($"WebSocket Error Device={remoteDevice}, Err{ex.Message}"); } catch (Exception ex) { _logger.Error(ex); } finally { await CleanUpAsync(remoteDevice); } }
async Task CleanUpAsync(WebSocketRemoteDevice remoteDevice) { if (remoteDevice == null) { return; } using (remoteDevice) { _logger.Warn($"Device {remoteDevice} disconnected."); await _remoteDeviceDisconenctedHandler .HandleAsync(remoteDevice) .ContinueWith(task => { if (task.Exception != null) { _logger.Error("remoteDeviceDisconenctedHandler throws exception", task.Exception); } }); } }