在上一节中,我们通过一个简单的Http服务器程序学习了Socket服务器端的编程.这一节将通过一个简单的网络蜘蛛程序(Spider)来学习Socket客户端的程序设计.
Spider是搜索引擎重要的组成部分,其基本的原理也比较简单,但要真正写一个能够用于搜索引擎的Spider绝非一件易事。
从本质来说,Spider就是一个网页下载程序,然后再对下载的网页进行分析,提取,整理,然后交给索引程序处理生成索引。
而对于Socket客户端来说,分以下几步来实现连接服务器端:
(1)创建IPEndPoint实例和套接字
IPAddress hostIp = Dns.GetHostEntry("http://www.").addresslist[0];
IPEndPoint ep = new IPEndPoint(hostIp, 80);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
(2)连接服务器端
try
{
client.Connect(ep);
}
catch (SocketException e)
{
Console.WriteLine(e.Message);
}
(3)发送请求
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("GET /index.html HTTP/1.1\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("Host:\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("Connection:Close\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("\r\n"));
(4)接收数据
StringBuilder recstr = new StringBuilder();
byte[] buff = new byte[1024];
int rCount=0;
while(true)
{
rCount = client.Receive(buff, buff.Length, SocketFlags.None); //读取数据
if (rCount > 0)
{
recstr.Append(ASCIIEncoding.ASCII.GetString(buff, 0, rCount));
}
else
break;
}
完整代码如下:
Code
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
;
.Sockets;
usingSystem.IO;
namespaceMyHttpClient
{
classProgram
{
staticvoidMain(string[]args)
{
IPAddresshostIp=Dns.GetHostEntry("www.").AddressList[0];
IPEndPointep=newIPEndPoint(hostIp,80);
Socketclient=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
client.Connect(ep);
}
catch(SocketExceptione)
{
Console.WriteLine(e.Message);
}
//发送请求
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("GET/index.htmlHTTP/1.1\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("Host:\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("Connection:Close\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("\r\n"));
StringBuilderrecstr=newStringBuilder();
byte[]buff=newbyte[1024];
intrCount=0;
while(true)
{
rCount=client.Receive(buff,buff.Length,SocketFlags.None);//读取数据
if(rCount>0)
{
recstr.Append(ASCIIEncoding.ASCII.GetString(buff,0,rCount));
}
else
break;
}
using(StreamWritersw=newStreamWriter(File.Create(@"c:\test.html")))
{
sw.Write(recstr.ToString());//写入文件
}
Console.WriteLine("下载成功!");
Console.Read();
}
}
}
运行以上程序,将会把华工的主页下载到你的c盘根目录下.这恐怕是一个最简单的Spider程序了.