WinForm程序中怎么用TcpClient(而不是WebClient)来访问一个Web页面?

医手 2008-09-04 03:51:36
WinForm程序中怎么用TcpClient(而不是WebClient)来访问一个Web页面?
...全文
126 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
brallow 2008-09-04
  • 打赏
  • 举报
回复
TCPClient只是一个访问的客户端组件,这个TCP访问的目标限制在这里:
TcpClient tc = new TcpClient("www.baidu.com", 80);
其中的第一个参数是域名,这个域名确定了在TCP通信的过程中的目标结点的IP。如果不修改这个地方,即使你修改发送的参数,比如:Get...等也是于事无补的。
比如你修改了发送参数为:
string[] L = new string[6];
L[0] = "GET /index.html HTTP/1.1";
L[1] = "Host:www.csdn.net";
L[2] = "Accept:*/*";
L[3] = "User-Agent:Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)";
L[4] = "Connection:Keep-Alive";
L[5] = "";
在实际发送时,这个数据包仍然发送到了www.baidu.com,baidu当然不会返回csdn网站上的内容(即使有,也是不正确的)。
因此,正确的作法是new一个TCPClient或者修改它的EndPoint属性,然后再发送。
医手 2008-09-04
  • 打赏
  • 举报
回复
谢谢, 顺便问一下TcpClient能不能用相同的端口去访问不同的网站?
给我的感觉是不要说相同的端口,就是同一个TcpClient对像也不能去访问不同的网站.
LQknife 2008-09-04
  • 打赏
  • 举报
回复
顶顶更健康
brallow 2008-09-04
  • 打赏
  • 举报
回复
使用这段代码,最后的byte[] page中收到了数据,具体的数据内容我就没有解释及输出了。

static void Main(string[] args)
{
string[] L = new string[6];
L[0] = "GET /index.html HTTP/1.1";
L[1] = "Host:www.baidu.com";
L[2] = "Accept:*/*";
L[3] = "User-Agent:Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)";
L[4] = "Connection:Keep-Alive";
L[5] = "";

int tLength = 0;

for (int i = 0; i < 6; i++)
{
string s = L[i];
//s += "\r\n";
tLength += s.Length;
}

byte[] data = new byte[tLength + 2 * 6];


int currentPos = 0;
for (int i = 0; i < 6; i++)
{
string s = L[i];
for (int j = 0; j < s.Length; j++)
{
data[currentPos] = (byte)s[j];
currentPos++;
}
data[currentPos] = (byte)'\r';
currentPos++;
data[currentPos] = (byte)'\n';
currentPos++;
}

TcpClient tc = new TcpClient("www.baidu.com", 80);
tc.Client.Send(data);

byte[] page = new byte[1024];

tc.Client.Receive(page);

}
brallow 2008-09-04
  • 打赏
  • 举报
回复
再参考这个:
http://www.vckbase.com/document/viewdoc/?id=1208
brallow 2008-09-04
  • 打赏
  • 举报
回复
简单,根据HTTP协议的具体要求实现!
参考这个,我试试看能否帖上个C#的代码;
http://www.edu.cn/20011207/3013221.shtml

111,120

社区成员

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

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

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