基于c#套接字的HTTP

本文关键字:HTTP 套接字 基于 | 更新日期: 2023-09-27 18:11:35

我正在尝试通过c#套接字发送HTTP请求并从服务器接收响应,并且我是这种语言的新手。

我写了以下代码(IP解析正确):

IPEndPoint RHost = new IPEndPoint(IP, Port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(RHost);
String HTTPRequestHeaders_String = "GET ?q=fdgdfg HTTP/1.0
Host: google.com
Keep-Alive: 300
Connection: Keep-Alive
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16
Referer: http://google.com/";
MessageBox.Show(HTTPRequestHeaders_String, "Request");
byte[] HTTPRequestHeaders = System.Text.Encoding.ASCII.GetBytes(HTTPRequestHeaders_String);
socket.Send(HTTPRequestHeaders, SocketFlags.None);
String Response = "";
byte[] buffer = new byte[(int) socket.ReceiveBufferSize];
int bytes;
do
{
    // On this lane program stops to react
    bytes = socket.Receive(buffer);
    // This line cannot be reached, tested with breakpoint
    Response += Encoding.ASCII.GetString(buffer, 0, bytes);
}
while (bytes >= 0);
MessageBox.Show(Response, "Response");

我做错了什么?我只需要加载完整的HTML页面,或至少几个字符的响应(我不能这样做)。

基于c#套接字的HTTP

如果您想要进行原始操作,我建议查看协议本身,http://www.w3.org/Protocols/HTTP/1.0/spec.html#Request

并尝试发送CRLF来终止请求;)

var webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream responseStream = webClient.OpenRead("http://www.google.com");
if (responseStream != null)
{
   var responseReader = new StreamReader(responseStream);
   string response = responseReader.ReadToEnd();
   MessageBox.Show(response);
}

我发现Mentalis Proxy对于理解套接字级别的Http请求/响应周期非常有帮助:http://www.mentalis.org/soft/projects/proxy/

TcpClient类一方面允许您完全控制请求(您将请求体创建为字符串),另一方面比低级套接字更容易使用。

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx