我对SNP一无所知。您的代码在接收部分有点混乱。我使用下面的示例来发送和读取 HTTP GET 请求的服务器响应。首先让我们看一下请求,然后检查响应。
HTTP GET 请求:
GET / HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
Accept: text/html
User-Agent: CSharpTests
string - "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\nAccept: text/html\r\nUser-Agent: CSharpTests\r\n\r\n"
服务器 HTTP 响应标头:
HTTP/1.1 200 OK
Date: Sun, 07 Jul 2013 17:13:10 GMT
Server: Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16
Last-Modified: Sat, 30 Mar 2013 11:28:59 GMT
ETag: \"ca-4d922b19fd4c0\"
Accept-Ranges: bytes
Content-Length: 202
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
string - "HTTP/1.1 200 OK\r\nDate: Sun, 07 Jul 2013 17:13:10 GMT\r\nServer: Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16\r\nLast-Modified: Sat, 30 Mar 2013 11:28:59 GMT\r\nETag: \"ca-4d922b19fd4c0\"\r\nAccept-Ranges: bytes\r\nContent-Length: 202\r\nKeep-Alive: timeout=5, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n"
我故意省略了服务器响应的主体,因为我们已经知道它正好是 202 字节,由响应标头中的 Content-Length 指定。
查看 HTTP 规范会发现 HTTP 标头以空的新行(“\r\n\r\n”)结尾。所以我们只需要搜索它。
让我们看看一些实际的代码。假设 System.Net.Sockets.Socket 类型的变量套接字。
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("127.0.0.1", 80);
string GETrequest = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\nAccept: text/html\r\nUser-Agent: CSharpTests\r\n\r\n";
socket.Send(Encoding.ASCII.GetBytes(GETrequest));
我们已经将请求发送到服务器,让我们接收并正确解析响应。
bool flag = true; // just so we know we are still reading
string headerString = ""; // to store header information
int contentLength = 0; // the body length
byte[] bodyBuff = new byte[0]; // to later hold the body content
while (flag)
{
// read the header byte by byte, until \r\n\r\n
byte[] buffer = new byte[1];
socket.Receive(buffer, 0, 1, 0);
headerString += Encoding.ASCII.GetString(buffer);
if (headerString.Contains("\r\n\r\n"))
{
// header is received, parsing content length
// I use regular expressions, but any other method you can think of is ok
Regex reg = new Regex("\\\r\nContent-Length: (.*?)\\\r\n");
Match m = reg.Match(headerString);
contentLength = int.Parse(m.Groups[1].ToString());
flag = false;
// read the body
bodyBuff = new byte[contentLength];
socket.Receive(bodyBuff, 0, contentLength, 0);
}
}
Console.WriteLine("Server Response :");
string body = Encoding.ASCII.GetString(bodyBuff);
Console.WriteLine(body);
socket.Close();
这可能是在 C# 中执行此操作的最糟糕的方法,在 .NET 中有大量类可以处理 HTTP 请求和响应,但如果您需要它,它仍然可以工作。