C#中用socket连接web服务器出现“远程主机强迫关闭了一个现有的连接”的错误,怎么处理

nickelzhang 2007-12-10 02:35:49
  public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnDownload_Click(object sender, EventArgs e)
{
string host = "www.baidu.com";
int port = 80;

string result = SocketSendReceive(host, port);
Console.WriteLine(result);
}
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;

// Get host related information.
hostEntry = Dns.GetHostEntry(server);

// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

tempSocket.Connect(ipe);

if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}

// This method requests the home page content for the specified server.
private static string SocketSendReceive(string server, int port)
{
string request = @"GET / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
Host: www.baidu.com.cn
Connection: Keep-Alive";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[1024];

// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(server, port);

if (s == null)
return ("Connection failed");


// Send request to the server.


// Receive the server home page content.
int bytes = 0;
string page = "Default HTML page on " + server + ":\r\n";

// The following will block until te page is transmitted.
s.Send(bytesSent, bytesSent.Length, 0);
//do
{
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);//运行到这里卡住!一段时间后出现错误
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
//while (bytes == 1024);

return page;
}
...全文
665 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
向着朝阳出发 2010-09-20
  • 打赏
  • 举报
回复
俺也遇到这样的问题了, 不知道该怎么解决, 应该是线程间的互斥吧。
zouqiang122 2007-12-10
  • 打赏
  • 举报
回复
up
zouqiang122 2007-12-10
  • 打赏
  • 举报
回复

110,571

社区成员

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

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

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