【发布时间】:2010-12-06 19:50:43
【问题描述】:
我正在尝试编写一个简单的控制台应用程序,它可以发布到页面并将返回的 html 输出到控制台。
我的代码有效,但它只返回部分响应。我能弄清楚使其工作的唯一方法是将字节缓冲区设置为我知道的大小,足以容纳返回的内容。
有没有办法检查缓冲区需要多大才能接收完整的响应?
这里是代码...
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();
【问题讨论】: