private void CleanUpServer(EtpServer server) { EtpServer s; _servers.TryRemove(server.SessionId, out s); Task t; _serverTasks.TryRemove(server.SessionId, out t); server.Dispose(); }
private async Task HandleListener(CancellationToken token) { try { // TODO: Handle server cap URL HttpListenerContext context = await _httpListener.GetContextAsync(); if (token.IsCancellationRequested) { CleanUpContext(context); return; } var headers = GetWebSocketHeaders(context.Request.Headers, context.Request.QueryString); if (!context.Request.IsWebSocketRequest) { CleanUpContext(context); return; } if (!EtpWebSocketValidation.IsWebSocketRequestUpgrading(headers)) { context.Response.StatusCode = (int)HttpStatusCode.UpgradeRequired; context.Response.StatusDescription = "Invalid web socket request"; CleanUpContext(context); return; } var preferredProtocol = EtpWebSocketValidation.GetPreferredSubProtocol(headers); if (preferredProtocol == null) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.StatusDescription = "Invalid web socket request"; CleanUpContext(context); return; } if (!EtpWebSocketValidation.IsEtpEncodingValid(headers)) { context.Response.StatusCode = (int)HttpStatusCode.PreconditionFailed; context.Response.StatusDescription = "Invalid etp-encoding header"; CleanUpContext(context); return; } HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(preferredProtocol); if (token.IsCancellationRequested) { webSocketContext.WebSocket.Dispose(); context.Response.Close(); return; } var server = new EtpServer(webSocketContext.WebSocket, ApplicationName, ApplicationVersion, headers); server.SupportedObjects = SupportedObjects; RegisterAll(server); _servers[server.SessionId] = server; _serverTasks[server.SessionId] = Task.Run(async() => { try { InvokeSessionConnected(server); await server.HandleConnection(token); } finally { InvokeSessionClosed(server); CleanUpServer(server); webSocketContext.WebSocket.Dispose(); CleanUpContext(context); } }, token); } catch (Exception ex) { if (!ex.ExceptionMeansConnectionTerminated()) { Log("Error: Exception caught when handling a websocket connection: {0}", ex.Message); Logger.DebugFormat("Exception caught when handling a websocket connection: {0}", ex); throw; } } }