早上好
我是C#程序员,我遇到了问题

我试图打开套接字以获取HTTP连接,并以字节流的形式读取页面
一切都对,
例如,要通过C#套接字获取google主页,
我遵循的步骤是:

1.打开一个流并连接到谷歌服务器:

Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
skt.Connect("www.google.com", 80);

2.准备请求并将其放入字节数组:
string hdrs = "GET / HTTP/1.1\r\n"
    + "Host: www.google.com\r\n\r\n";
byte[] req_as_bytes = Encoding.UTF8.GetBytes(hdrs);

3,发送HTTP请求
skt.Send(req_as_bytes);

4.收到回复:
byte[] data = new byte[1024 * 200]; // 200 kilo bytes
int t = skt.Receive(data);
Console.WriteLine(Encoding.UTF8.GetString(data,0,t));

但是当我将http方法从[GET]更改为[CONNECT]时,
回应将是空的!或没有从服务器接收到数据
新的请求是:
string hdrs = "CONNECT www.google.com:443 HTTP/1.1\r\n"
    + "Host: www.google.com:443\r\n"
    + "Proxy-Connection: keep-alive\r\n\r\n";

谁能帮我?

完整代码:
static void Main(string[] args)
{
    Socket skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    skt.Connect("www.google.com", 443);
    string hdrs = "CONNECT www.google.com:443 HTTP/1.1\r\n"
        + "Host: www.google.com:443\r\n"
        + "Proxy-Connection: keep-alive\r\n\r\n";
    byte[] req_as_bytes = Encoding.UTF8.GetBytes(hdrs);
    skt.Send(req_as_bytes);
    byte[] data = new byte[1024 * 200]; // 200 kilo bytes
    int t = skt.Receive(data);
    Trace.WriteLine(Encoding.UTF8.GetString(data, 0, t);
    skt.Shutdown(SocketShutdown.Both);
    skt.Close();
}

谢谢你 ...
马哈德

最佳答案

如果您确实要实现HTTPS服务器,则需要阅读RFC

顺便说一句,它已经在.NET中实现:System.Net.HttpListener

10-06 06:36