Exemple #1
0
        private void HandleTcpClientAccepted(IAsyncResult ar)
        {
            if (IsRunning)
            {
                TcpListener tcpListener = (TcpListener)ar.AsyncState;

                TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);
                byte[]    buffer    = new byte[tcpClient.ReceiveBufferSize];

                SimpleProtocolFilter prot           = new SimpleProtocolFilter();
                TcpClientState       internalClient = new TcpClientState(tcpClient, buffer, prot);
                lock (this.clients) {
                    this.clients.Add(internalClient);
                    RaiseClientConnected(tcpClient);
                }

                NetworkStream networkStream = internalClient.NetworkStream;
                networkStream.BeginRead(
                    internalClient.Buffer,
                    0,
                    internalClient.Buffer.Length,
                    HandleDatagramReceived,
                    internalClient);

                tcpListener.BeginAcceptTcpClient(
                    new AsyncCallback(HandleTcpClientAccepted), ar.AsyncState);
            }
        }
Exemple #2
0
        private void HandleTcpClientAccepted(IAsyncResult ar)
        {
            if (!IsRunning)
            {
                return;
            }

            TcpListener tcpListener = (TcpListener)ar.AsyncState;

            TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar);

            if (!tcpClient.Connected)
            {
                return;
            }

            byte[] buffer                       = new byte[tcpClient.ReceiveBufferSize];
            SimpleProtocolFilter prot           = new SimpleProtocolFilter();
            TcpClientState       internalClient = new TcpClientState(tcpClient, buffer, prot);

            // add client connection to cache
            string tcpClientKey = internalClient.TcpClient.Client.RemoteEndPoint.ToString();

            _clients.AddOrUpdate(tcpClientKey, internalClient, (n, o) =>
            {
                return(internalClient);
            });
            RaiseClientConnected(tcpClient);

            // begin to read data
            NetworkStream networkStream = internalClient.NetworkStream;

            ContinueReadBuffer(internalClient, networkStream);

            // keep listening to accept next connection
            ContinueAcceptTcpClient(tcpListener);
        }