我想寫一個簡單的控制檯應用程序,POST到一個頁面並輸出返回的HTML到控制檯。C#套接字編程 - 如何確定接收緩衝區的大小
我的代碼有效,但它只返回響應的一部分。我可以想出使其工作的唯一方法是將字節緩衝區設置爲我知道足夠大以便返回內容的大小。
有沒有辦法檢查緩衝區需要多大來獲得完整的響應?
這裏是代碼...
Uri uri = new Uri(@"http://bobssite/");
// Get the IPAddress of the website we are going to and create the EndPoint
IPAddress ipAddress = Dns.GetHostEntry(uri.Host).AddressList[0];
IPEndPoint endPoint = new IPEndPoint(ipAddress, 80);
// Create a new Socket instance and open the socket for communication
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socket.Connect(endPoint);
// Attempt to send the request
int byteCount = 0;
try
{
string requestString =
"POST " + uri.PathAndQuery + " HTTP/1.1\r\n" +
"Host: " + uri.Host + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: 11\r\n" +
"\r\n" +
"user=bob";
byte[] bytesToSend = Encoding.ASCII.GetBytes(requestString);
byteCount = socket.Send(bytesToSend, SocketFlags.None);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
// Attempt to receive the response
if (byteCount > 0)
{
byte[] bytesReceived = new byte[256];
try
{
byteCount = socket.Receive(bytesReceived, SocketFlags.None);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("HELP!! --> " + e.Message);
}
// Out the html we received
string html = Encoding.ASCII.GetString(bytesReceived);
Console.WriteLine(html);
}
else
{
Console.WriteLine("byteCount is zero!");
}
Console.Read();
我知道我可以用Web客戶端或HttpWebRequest的做到這一點很容易,但我強迫自己使用Socket類。 – thiag0 2010-12-06 19:59:44