private void HandleTcpClientAccepted(IAsyncResult ar) { if (IsRunning) { TcpListener tcpListener = (TcpListener)ar.AsyncState; TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar); if (!tcpClient.Connected) { return; } byte[] buffer = new byte[tcpClient.ReceiveBufferSize]; // add client connection to cache TcpClientState tcpClientState = new TcpClientState(tcpClient, buffer); lock (this._clients) { string clientKey = tcpClientState.TcpClient.Client.RemoteEndPoint.ToString(); this._clients.AddOrUpdate(clientKey, tcpClientState, (c, t) => { return(tcpClientState); }); RaiseClientConnected(tcpClientState); } // begin to read data NetworkStream networkStream = tcpClientState.NetworkStream; ContinueReadBuffer(tcpClientState, networkStream); // keep listening to accept next connection ContinueAcceptTcpClient(tcpListener); } }
private void HandleDatagramReceived(IAsyncResult ar) { if (!IsRunning) { return; } try { TcpClientState tcpClientState = (TcpClientState)ar.AsyncState; if (!tcpClientState.TcpClient.Connected) { return; } NetworkStream networkStream = tcpClientState.NetworkStream; int numberOfReadBytes = 0; try { // if the remote host has shutdown its connection, // read will immediately return with zero bytes. numberOfReadBytes = networkStream.EndRead(ar); } catch (Exception ex) { Logger.Error("", ex); numberOfReadBytes = 0; } if (numberOfReadBytes == 0) { // connection has been closed string tcpClientKey = tcpClientState.TcpClient.Client.RemoteEndPoint.ToString(); _clients.TryRemove(tcpClientKey, out TcpClientState internalClientToBeThrowAway); RaiseClientDisconnected(tcpClientState.TcpClient); return; } // received byte and trigger event notification byte[] receivedBytes = new byte[numberOfReadBytes]; Buffer.BlockCopy( tcpClientState.Buffer, 0, receivedBytes, 0, numberOfReadBytes); RaiseDatagramReceived(tcpClientState.TcpClient, receivedBytes); RaisePlaintextReceived(tcpClientState.TcpClient, receivedBytes); // continue listening for tcp datagram packets ContinueReadBuffer(tcpClientState, networkStream); } catch (InvalidOperationException ex) { Logger.Error("", ex); } }
private void ContinueReadBuffer(TcpClientState tcpClientState, NetworkStream networkStream) { try { networkStream.BeginRead( tcpClientState.Buffer, 0, tcpClientState.Buffer.Length, HandleDatagramReceived, tcpClientState); } catch (ObjectDisposedException ex) { Logger.Error("", ex); } }
private void RaiseClientConnected(TcpClientState tcpClientState) { ClientConnected?.Invoke(this, new TcpClientConnectedEventArgs(tcpClientState.TcpClient)); }