用sslStream类包装在ssl流中

时间:2013-09-04 15:52:06

标签: sockets ssl tcp https sslstream

当我运行以下代码时,会发生错误

    string host = "www.google.com";
    int proxyPort = 443;//443;

    byte[] buffer = new byte[2048];
    int bytes;

    // Connect socket
    TcpClient client = new TcpClient(host, proxyPort);
    NetworkStream stream = client.GetStream();

    // Establish Tcp tunnel
    byte[] tunnelRequest = Encoding.UTF8.GetBytes(String.Format("CONNECT {0}:443  HTTP/1.1\r\nHost: {0}\r\n\r\n", host));
    stream.Write(tunnelRequest, 0, tunnelRequest.Length);
    stream.Flush();

    // Read response to CONNECT request
    // There should be loop that reads multiple packets
    bytes = stream.Read(buffer, 0, buffer.Length);
    Console.Write(Encoding.UTF8.GetString(buffer, 0, bytes));

    // Wrap in SSL stream
    SslStream sslStream = new SslStream(stream);
    sslStream.AuthenticateAsClient(host);

错误发生在这一行

    sslStream.AuthenticateAsClient(host);

错误是:无法将数据写入传输连接:已建立的连接已被主机中的软件中止。

我该如何解决这个问题?感谢

1 个答案:

答案 0 :(得分:0)

您正在向HTTPS服务器发送CONNECT,该服务器正确关闭连接,因为它不是有效的HTTPS握手。

CONNECT仅发送到上游代理(为了通过代理隧道);它是从不发送到原始服务器本身。即使您使用代理,您读取CONNECT响应的代码也是错误的,并且不太可能有效。

你有没有考虑让我为你辛勤工作? http://fiddler2.com/core/