socket发送http请求的问题

qinjs 2006-07-06 05:11:24
代码如下:
//调用的代码
private void btTest_Click(object sender, System.EventArgs e)
{
a_strServer = "http://WWW.CSDN.NET";
a_strRequest = "GET /test.htm HTTP/1.1";
//txtSource.Text = this.Get_Socket_Request(a_strServer,a_strRequest,80,"Connection: Keep-Alive");
txtSource.Text = this.Get_Socket_Request(a_strServer,a_strRequest,80,"Connection: Close");
}

//发送请求的函数
private string Get_Socket_Request(string a_strServer , string a_strRequest , Int32 a_intPort , string Connection)
//通过同server建立tcp/ip连接,发送socket命令
{
Encoding ASCII = Encoding.Default ;
string Get = a_strRequest + "\r\n" + "Accept: */*\r\n";
Get = Get + "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)\r\n";
Get = Get + "Host: " + a_strServer.Substring(7 ,a_strServer.Length - 7) + "\r\n" + Connection +"\r\n\r\n";

Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
String strRetPage = null;

IPHostEntry IPHost = Dns.Resolve(a_strServer.Substring(7 ,a_strServer.Length - 7));
IPAddress[] hostadd = IPHost.AddressList;

IPEndPoint EPhost = new IPEndPoint(hostadd[0], a_intPort);

Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

s.Connect(EPhost);
if (!s.Connected)
{
strRetPage = "Unable to connect to host";
return strRetPage;
}

s.Send(ByteGet, ByteGet.Length, 0);

Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);

while (bytes > 0)
{
bytes = s.Receive(RecvBytes, RecvBytes.Length, 0); //问题在这句
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
}

  s.Shutdown ( SocketShutdown.Both ) ;
s.Close ( ) ;

return strRetPage ;
}
****************************************************
问题:
当 Connection: 为 Close 时,函数Get_Socket_Request可以正常运行完成,
而当 Connection: 为 Keep-Alive 时,运行到 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0); 这句就停在这里,应该是阻塞住了.
请问这是什么原因? 为 Keep-Alive 时,应该怎么才能够可以正常运行完不停止下来?
...全文
209 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jeremychen001181 2006-07-08
  • 打赏
  • 举报
回复
出现这样的问题多半是,你书写的HTTP头格式不正确造成的。
qinjs 2006-07-06
  • 打赏
  • 举报
回复
因为发送的HTTP头在HttpWebRequest里面不能自由定义.这个问题见
http://community.csdn.net/Expert/topic/4860/4860278.xml?temp=.5272028
henryfan1 2006-07-06
  • 打赏
  • 举报
回复
为什么不用HttpWebRequest,这样不是更方便吗?

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧