예제 #1
0
파일: TcpServer.cs 프로젝트: Shpek/ChaosRpc
        private void OnClientAccepted(IAsyncResult ar)
        {
            var           listener      = (TcpListener)ar.AsyncState;
            Socket        socket        = null;
            TcpSession    session       = null;
            SslConnection sslConnection = null;

            try {
                socket = listener.EndAcceptSocket(ar);

                if (SecureServer)
                {
                    sslConnection = new SslConnection
                    {
                        Socket = socket,
                    };

                    sslConnection.SslStream = new SslStream(
                        new NetworkStream(socket, true), false, CertificateValidationCallback);

                    sslConnection.SslStream.BeginAuthenticateAsServer(
                        ServerCertificate, ClientCertificateReqired,
                        SslProtocols.Tls, true, OnClientAutenticated,
                        sslConnection);
                }
                else
                {
                    session = new TcpSession(socket, new NetworkStream(socket, true));

                    try {
                        if (OnClientConnected != null)
                        {
                            OnClientConnected(session);
                        }
                    } catch (Exception e) {
                        Console.WriteLine(e);
                        // ignored
                    }

                    session.Start();
                }
            } catch (Exception e) {
                try {
                    if (OnError != null)
                    {
                        OnError(e);
                    }
                } catch (Exception) {
                    // ignored
                }

                if (session != null)
                {
                    session.Close();
                }
                else if (sslConnection != null)
                {
                    if (sslConnection.SslStream != null)
                    {
                        sslConnection.SslStream.Close();
                    }
                    else
                    {
                        sslConnection.Socket.Close();
                    }
                }
                else if (socket != null)
                {
                    socket.Close();
                }
            }

            listener.BeginAcceptTcpClient(OnClientAccepted, listener);
        }