socket发送http请求的问题

qinjs qinjs 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
代码如下:
//调用的代码
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 时,应该怎么才能够可以正常运行完不停止下来?
...全文
评论 3
收藏 已收藏
分享
返回顶部
qinjs
C# 111,129 成员 642,540 内容