public void Disconnect() { if (connection != null && connection.Connected) { lock (this) { if (connection != null && connection.Connected) { autoreconnect = false; clientSocket.Close(); clientSocket.Dispose(); clientSocket = null; connection.Close(); connection = null; log.Info("Client disconected"); Complete(); observers = new ConcurrentList <IObserver <IConnection> >(); } } } }
private void ClientConnected(IAsyncResult result) { if (!stopped) { Socket clientSocket = null; TcpConnection connection = null; try { clientSocket = serverSocket.EndAccept(result); connection = new TcpConnection(clientSocket, new FramingMessageProtocol()); log.InfoFormat("New connection established: {0}", connection); TcpSocketConnected(connection); serverSocket.BeginAccept(ClientConnected, this);// Continue accepting } catch (SocketException ex) { if (connection != null) { connection.Close(); connections.Remove(connection); } else if (clientSocket != null) { clientSocket.Close(); clientSocket.Dispose(); } log.Error("Socket exception.", ex); OnException(ex); AcceptNextClient(); } catch (Exception ex) { log.Fatal("Unexpected error.", ex); if (connection != null) { connection.Close(); connections.Remove(connection); } else if (clientSocket != null) { clientSocket.Close(); } OnException(ex); AcceptNextClient(); } } }
private void TcpSocketConnected(TcpConnection tcpSocket) { connections.Add(tcpSocket); tcpSocket.Subscribe(new CompletedObserver(() => connections.Remove(tcpSocket))); foreach (var item in observers) { item.OnNext(tcpSocket); } }