void OnDataReceivedByService(TcpStreamChannel channel)
        {
            while (channel.IsConnected)
            {
                var received = channel.InputStream.ReadByte();
                if (received >= 0)
                {
                    channel.OutputStream.WriteByte((byte)received);
                }

                if (channel.InputStream.Length == 0)
                {
                    channel.OutputStream.Flush();
                }
            }
        }
        void OnClientAcceptedByService(TcpStreamChannel channel)
        {
            if (_stub1 == null)
            {
                _stub1 = channel;
            }
            else if (_stub2 == null)
            {
                _stub2 = channel;
            }
            else
            {
                Assert.Fail("too many accepted clients");
            }

            channel.Start(OnDataReceivedByService, OnServiceChannelDisconnected);
            _serviceConnectedEvent.Set();
        }
        /// <summary>
        /// A client has connected. Called from socket on threadpool thread.
        /// </summary>
        private void OnAcceptNewClient(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                do
                {
                    if (_disposed || e.SocketError != SocketError.Success)
                    {
                        LatestException = new SocketException((int)e.SocketError);
                        return;
                    }

                    var channel = new TcpStreamChannel(e.AcceptSocket);
                    e.AcceptSocket = null;

                    // Callback to user. User has to start the new channel.
                    _onClientAcceptedAction(channel); 
                }
                while (!_disposed && !_listenSocket.AcceptAsync(_acceptEventArg));
            }
            catch (Exception ex)
            {
                Dispose();
                LatestException = ex;
            }
        }
        void OnServiceChannelDisconnected(TcpStreamChannel channel)
        {

        }
 public void TestInitialize()
 {
     _stub1 = null;
     _stub2 = null;
     _service = new TcpStreamService(0, OnClientAcceptedByService);
 }
 void OnLargeArrayReceivedByClient(TcpStreamChannel channel)
 {
     var reader = new BinaryReader(channel.InputStream);
     _receivedBytes = reader.ReadBytes(_expectedCount);
     _clientReceivedEvent.Set();
 }
        void OnClientChannelDisconnected(TcpStreamChannel channel)
        {

        }
 void OnDataReceivedByClient(TcpStreamChannel channel)
 {
     Thread.Sleep(_receiveDelay);
     var reader = new BinaryReader(channel.InputStream);
     _receivedDec = reader.ReadDecimal();
     _clientReceivedEvent.Set();
 }