在上一節中,我們通過一個簡單的Http伺服器程式學習了Socket伺服器端的編程.這一節將通過一個簡單的網路蜘蛛程式(Spider)來學習Socket用戶端的程式設計.
Spider是搜尋引擎重要的組成部分,其基本的原理也比較簡單,但要真正寫一個能夠用於搜尋引擎的Spider絕非一件易事。
從本質來說,Spider就是一個網頁下載程式,然後再對下載的網頁進行分析,提取,整理,然後交給索引程式處理產生索引。
而對於Socket用戶端來說,分以下幾步來實現串連伺服器端:
(1)建立IPEndPoint執行個體和通訊端
IPAddress hostIp = Dns.GetHostEntry("http://www.hust.edu.cn").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:hust.edu.cn\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
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace MyHttpClient
{
class Program
{
static void Main(string[] args)
{
IPAddress hostIp = Dns.GetHostEntry("www.hust.edu.cn").AddressList[0];
IPEndPoint ep = new IPEndPoint(hostIp, 80);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
client.Connect(ep);
}
catch (SocketException e)
{
Console.WriteLine(e.Message);
}
//發送請求
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("GET /index.html HTTP/1.1\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("Host:hust.edu.cn\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("Connection:Close\r\n"));
client.Send(Encoding.GetEncoding("us-ascii").GetBytes("\r\n"));
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;
}
using (StreamWriter sw = new StreamWriter(File.Create(@"c:\test.html")))
{
sw.Write(recstr.ToString()); //寫入檔案
}
Console.WriteLine("下載成功!");
Console.Read();
}
}
}
運行以上程式,將會把華工的首頁下載到你的c盤根目錄下.這恐怕是一個最簡單的Spider程式了.