public async Task HandleConnectionAsync(CancellationToken cancellation) { _cancellation = cancellation; List <UnsubscribeAction> unsubs = new List <UnsubscribeAction>(); var connectionId = GetConnectionId(_ws); var sessionId = GetSessionId(_ws); try { _log.Info("Starting session '{0}' at connection '{1}'", sessionId, connectionId); unsubs.Add(_queue.SubscribeHandler <IConnectionEvent>(msg => { lock (_ws) { using (var wsmsg = _ws.CreateMessageWriter(WebSocketMessageType.Text)) _serializer.Serialize(msg, wsmsg); } }, con => _ws.IsConnected && con.ConnectionId == connectionId)); _queue.Publish(new UserConnectionEvent(connectionId, sessionId)); while (_ws.IsConnected && !_cancellation.IsCancellationRequested) { var msg = await _ws.ReadMessageAsync(_cancellation).ConfigureAwait(false); if (msg != null) { Type type; var queueRequest = _serializer.Deserialize(msg, out type); queueRequest.ConnectionId = connectionId; _queue.Publish(queueRequest, type); } } } catch (Exception aex) { _log.Error("Error Handling connection", aex.GetBaseException()); try { _ws.Close(); } catch { } } finally { _log.Debug("Session '{0}' with connection '{1}' disconnected", sessionId, connectionId); foreach (var unsub in unsubs) { unsub(); } _ws.Dispose(); _queue.Publish(new ConnectionDisconnectedRequest(connectionId, sessionId)); } }
public async Task HandleConnectionAsync(CancellationToken cancellation) { _cancellation = cancellation; var unsubs = new List <UnsubscribeAction>(); var connectionId = GetConnectionId(_ws); var sessionId = GetSessionId(_ws); var authClient = AddTerminalClient(_ws); try { _log.Info("Starting session '{0}' at connection '{1}'", sessionId, connectionId); unsubs.Add(_queue.SubscribeHandler <IConnectionEvent>(msg => { lock (_ws) { using (var wsmsg = _ws.CreateMessageWriter(WebSocketMessageType.Text)) _serializer.Serialize(msg, wsmsg); } }, con => _ws.IsConnected && con.ConnectionId == connectionId)); _queue.Publish(new UserConnectionEvent(connectionId, sessionId)); while (_ws.IsConnected && !_cancellation.IsCancellationRequested) { Console.WriteLine(authClient.Authenticated); var msg = await _ws.ReadMessageAsync(_cancellation).ConfigureAwait(false); if (msg == null) { continue; } Type type; var queueRequest = _serializer.Deserialize(msg, out type); Console.WriteLine(queueRequest); queueRequest.ConnectionId = connectionId; _queue.Publish(queueRequest, type); } } catch (Exception aex) { _log.Error("Error Handling connection", aex.GetBaseException()); try { _ws.Close(); } catch { } } finally { Console.WriteLine("Session '{0}' with connection '{1}' disconnected", sessionId, connectionId); foreach (var client in TerminalClients) { if (client.Value.Client != _ws) { continue; } AuthClient temp = null; TerminalClients.TryRemove(client.Key, out temp); Console.WriteLine("Disconnection from " + _ws.RemoteEndpoint); } foreach (var unsub in unsubs) { unsub(); } _ws.Dispose(); _queue.Publish(new ConnectionDisconnectedRequest(connectionId, sessionId)); } }