Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#SSLStream读取函数引发IOException_C#_Ioexception_Sslstream - Fatal编程技术网

C#SSLStream读取函数引发IOException

C#SSLStream读取函数引发IOException,c#,ioexception,sslstream,C#,Ioexception,Sslstream,我正在尝试创建自己的HTTPS代理服务器。 由于某种原因,我在尝试读取sslstream对象时遇到了一个异常。 这是: System.dll中发生“System.IO.IOException”类型的未处理异常 其他信息:无法从传输连接读取数据:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机没有响应 这是我的密码: public Server() { m_portnumber = 4434; m_tcpliste

我正在尝试创建自己的HTTPS代理服务器。 由于某种原因,我在尝试读取sslstream对象时遇到了一个异常。 这是:

System.dll中发生“System.IO.IOException”类型的未处理异常

其他信息:无法从传输连接读取数据:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机没有响应

这是我的密码:

    public Server()
    {
        m_portnumber = 4434;
        m_tcplistener = new TcpListener(IPAddress.Any, m_portnumber);
        m_cert = createCertificate();
    }
    public void start()
    {
        m_tcplistener.Start();
        while (true)
        {
            TcpClient client = m_tcplistener.AcceptTcpClient();
            ClientHandler(client);
        }
    }

    private void ClientHandler(TcpClient client)
    {
        // A client has connected. Create the 
        // SslStream using the client's network stream.
        SslStream sslStream = new SslStream(
            client.GetStream(), false);
        // Authenticate the server but don't require the client to authenticate.
        try
        {
            sslStream.AuthenticateAsServer(m_cert,
                false, SslProtocols.Tls, true);
            // Display the properties and settings for the authenticated stream.
            DisplaySecurityLevel(sslStream);
            DisplaySecurityServices(sslStream);
            DisplayCertificateInformation(sslStream);
            DisplayStreamProperties(sslStream);

            // Set timeouts for the read and write to 5 seconds.
            sslStream.ReadTimeout = 5000;
            sslStream.WriteTimeout = 5000;
            // Read a message from the client.   
            Console.WriteLine("Waiting for client message...");
            string messageData = ReadMessage(sslStream);
            Console.WriteLine("Received: {0}", messageData);
        }
        catch (AuthenticationException e)
        {
            Console.WriteLine("Exception: {0}", e.Message);
            if (e.InnerException != null)
            {
                Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
            }
            Console.WriteLine("Authentication failed - closing the connection.");
            sslStream.Close();
            client.Close();
            return;
        }
        finally
        {
            // The client stream will be closed with the sslStream
            // because we specified this behavior when creating
            // the sslStream.
            sslStream.Close();
            client.Close();
        }
    }
    static string ReadMessage(SslStream sslStream)
    {
        // Read the  message sent by the server.
        // The end of the message is signaled using the
        // "<EOF>" marker.
        byte[] buffer = new byte[2048];
        StringBuilder messageData = new StringBuilder();
        int bytes = -1;
        do
        {
            bytes = sslStream.Read(buffer, 0, buffer.Length);

            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
            decoder.GetChars(buffer, 0, bytes, chars, 0);
            messageData.Append(chars);
            // Check for EOF.
            if (messageData.ToString().IndexOf("<EOF>") != -1)
            {
                break;
            }
        } while (bytes != 0);

        return messageData.ToString();
    }
    static void DisplaySecurityLevel(SslStream stream)
    {
        Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
        Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
        Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
        Console.WriteLine("Protocol: {0}", stream.SslProtocol);
    }
    static void DisplaySecurityServices(SslStream stream)
    {
        Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
        Console.WriteLine("IsSigned: {0}", stream.IsSigned);
        Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
    }
    static void DisplayStreamProperties(SslStream stream)
    {
        Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
        Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
    }
    static void DisplayCertificateInformation(SslStream stream)
    {
        Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

        X509Certificate localCertificate = stream.LocalCertificate;
        if (stream.LocalCertificate != null)
        {
            Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                localCertificate.Subject,
                localCertificate.GetEffectiveDateString(),
                localCertificate.GetExpirationDateString());
        }
        else
        {
            Console.WriteLine("Local certificate is null.");
        }
        // Display the properties of the client's certificate.
        X509Certificate remoteCertificate = stream.RemoteCertificate;
        if (stream.RemoteCertificate != null)
        {
            Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                remoteCertificate.Subject,
                remoteCertificate.GetEffectiveDateString(),
                remoteCertificate.GetExpirationDateString());
        }
        else
        {
            Console.WriteLine("Remote certificate is null.");
        }
    }
    private static void DisplayUsage()
    {
        Console.WriteLine("To start the server specify:");
        Console.WriteLine("serverSync certificateFile.cer");
        Environment.Exit(1);
    }

    private X509Certificate createCertificate()
    {
        byte[] c = Certificate.CreateSelfSignCertificatePfx(
                   "CN=localhost", //host name
                    DateTime.Parse("2015-01-01"), //not valid before
                    DateTime.Parse("2020-01-01"), //not valid after
                    "sslpass"); //password to encrypt key file
        using (BinaryWriter binWriter = new BinaryWriter(File.Open(@"cert.pfx", FileMode.Create)))
        {
            binWriter.Write(c);
        }
        return new X509Certificate2(@"cert.pfx", "sslpass");
    }
}
公共服务器()
{
m_portnumber=4434;
m_tcplistener=新的tcplistener(IPAddress.Any,m_端口号);
m_cert=createCertificate();
}
公开作废开始()
{
m_tcplistener.Start();
while(true)
{
TcpClient client=m_tcplistener.AcceptTcpClient();
ClientHandler(客户);
}
}
私有无效客户端处理程序(TCP客户端)
{
//客户端已连接。请创建
//SslStream使用客户端的网络流。
SslStream SslStream=新SslStream(
client.GetStream(),false);
//对服务器进行身份验证,但不要求客户端进行身份验证。
尝试
{
SSL流认证服务器(m_证书,
假,SslProtocols.Tls,真);
//显示已验证流的属性和设置。
显示SecurityLevel(sslStream);
DisplaySecurityServices(sslStream);
显示证书信息(SSL流);
DisplayStreamProperties(sslStream);
//将读取和写入的超时设置为5秒。
sslStream.ReadTimeout=5000;
sslStream.WriteTimeout=5000;
//从客户端读取消息。
Console.WriteLine(“等待客户端消息…”);
字符串messageData=ReadMessage(sslStream);
WriteLine(“接收:{0}”,messageData);
}
捕获(身份验证异常e)
{
WriteLine(“异常:{0}”,e.Message);
如果(例如,InnerException!=null)
{
WriteLine(“内部异常:{0}”,e.InnerException.Message);
}
WriteLine(“身份验证失败-关闭连接”);
sslStream.Close();
client.Close();
返回;
}
最后
{
//客户端流将使用sslStream关闭
//因为我们在创建时指定了此行为
//SSL流。
sslStream.Close();
client.Close();
}
}
静态字符串读取消息(SslStream SslStream)
{
//阅读服务器发送的消息。
//使用
//”“马克。
字节[]缓冲区=新字节[2048];
StringBuilder messageData=新建StringBuilder();
int字节=-1;
做
{
字节=sslStream.Read(缓冲区,0,缓冲区长度);
//使用Decoder类将字节转换为UTF8
//如果一个字符跨越两个缓冲区。
解码器解码器=Encoding.UTF8.GetDecoder();
char[]chars=new char[decoder.GetCharCount(缓冲区,0,字节)];
GetChars(缓冲区,0,字节,字符,0);
messageData.Append(字符);
//检查EOF。
if(messageData.ToString().IndexOf(“”!=-1)
{
打破
}
}while(字节!=0);
返回messageData.ToString();
}
静态void DisplaySecurityLevel(SslStream流)
{
WriteLine(“密码:{0}强度{1}”,stream.cipheragorithm,stream.CipherStrength);
WriteLine(“Hash:{0}strength{1}”,stream.HashAlgorithm,stream.HashStrength);
WriteLine(“密钥交换:{0}强度{1}”,stream.keychangeAlgorithm,stream.keychangeStrength);
WriteLine(“协议:{0}”,stream.SslProtocol);
}
静态void DisplaySecurityServices(SslStream流)
{
WriteLine(“已验证:{0}作为服务器?{1}”,stream.IsAuthenticated,stream.IsServer);
WriteLine(“IsSigned:{0}”,stream.IsSigned);
WriteLine(“已加密:{0}”,stream.IsEncrypted);
}
静态void DisplayStreamProperties(SslStream流)
{
WriteLine(“可以读取:{0},写入{1}”,stream.CanRead,stream.CanWrite);
WriteLine(“Can超时:{0}”,stream.CanTimeout);
}
静态无效显示证书信息(SSL流)
{
WriteLine(“已检查的证书吊销列表:{0}”,stream.CheckCertRevocationStatus);
X509Certificate localCertificate=stream.localCertificate;
if(stream.LocalCertificate!=null)
{
WriteLine(“本地证书已颁发给{0},有效期从{1}到{2}”,
localCertificate.Subject,
localCertificate.GetEffectiveDateString(),
localCertificate.GetExpirationDateString());
}
其他的
{
WriteLine(“本地证书为空”);
}
//显示客户端证书的属性。
X509Certificate-remoteCertificate=stream.remoteCertificate;
if(stream.RemoteCertificate!=null)
{
WriteLine(“远程证书已颁发给{0},从{1}到{2}有效。”,
远程证书。主题,
remoteCertificate.GetEffectiveDateString(),
remoteCertificate.GetExpirationDateString());
}
其他的
{
WriteLine(“远程证书为空”);
}
}
私有静态void DisplayUsage()
{
Console.WriteLine(“以启动服务器