Exemplo n.º 1
0
 void ReadAsynchronously(StreamContext context)
 {
     context.Stream.BeginRead(context.Buffer, 0, context.Buffer.Length, OnAsynchronousRead, context);
 }
Exemplo n.º 2
0
        void ProcessClient(TcpClient localClient)
        {
            LocalStream = new SslStream(localClient.GetStream(), false);
            LocalStream.AuthenticateAsServer(ServerCertificate);

            TcpClient remoteClient = new TcpClient();
            remoteClient.Connect(RemoteEndpoint);
            RemoteStream = new SslStream(remoteClient.GetStream(), false, new RemoteCertificateValidationCallback(TrustAllCertificates));
            RemoteStream.AuthenticateAsClient(TargetHost);

            ServerEventHandler.OnConnect();

            StreamContext localContext = new StreamContext(LocalStream);
            StreamContext remoteContext = new StreamContext(RemoteStream);

            ReadAsynchronously(remoteContext);

            while (Running)
            {
                int bytesRead;
                try
                {
                    bytesRead = LocalStream.Read(localContext.Buffer, 0, localContext.Buffer.Length);
                    if (bytesRead == 0)
                    {
                        CloseStreams();
                        ServerEventHandler.OnLocalDisconnect();
                        return;
                    }
                }
                catch (IOException)
                {
                    CloseStreams();
                    ServerEventHandler.OnLocalDisconnect();
                    return;
                }
                try
                {
                    byte[] data = localContext.Buffer.Take(bytesRead).ToArray();
                    RemoteStream.Write(data);
                    ServerEventHandler.OnClientToServerData(data);
                }
                catch (IOException)
                {
                    CloseStreams();
                    ServerEventHandler.OnRemoteDisconnect();
                    return;
                }
            }
        }