構(gòu)造.NET環(huán)境下的網(wǎng)頁下載器 (2)
發(fā)布時間:2008-09-07 閱讀數(shù): 次 來源:網(wǎng)樂原科技
三.網(wǎng)頁下載器實例介紹:
最后,我就綜合以上.NET網(wǎng)絡(luò)編程的一些知識,向大家展示一個很好的實例。該實例是一個運用Socket的基于同步模式的客戶端應(yīng)用程序,它首先通過解析服務(wù)器的IP地址建立一個終結(jié)點,同時創(chuàng)建一個基于流套接字的Socket連接,其運用的協(xié)議是TCP協(xié)議。通過該Socket就可以發(fā)送獲取網(wǎng)頁的命令,再通過該Socket獲得服務(wù)器上默認的網(wǎng)頁,最后通過文件流將獲得的數(shù)據(jù)寫入本機文件。這樣就完成了網(wǎng)頁的下載工作了,程序運行的效果如下所示:
<img align="center" src="http://developer.ccidnet.com/pub/attachment/2003/8/250063.gif">
程序的代碼如下:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
namespace SocketSample
{
/// <summary>
/// Form1 的摘要說明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button Download;
private System.Windows.Forms.TextBox ServerAddress;
private System.Windows.Forms.TextBox Filename;
/// <summary>
/// 必需的設(shè)計器變量。
/// </summary>
private System.ComponentModel.Container
components = null;
public Form1()
{
//
// Windows 窗體設(shè)計器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent
// 調(diào)用后添加任何構(gòu)造函數(shù)代碼
}
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// 設(shè)計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內(nèi)容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.
Forms.Label();
this.label2 = new System.Windows.
Forms.Label();
this.Download = new System.Windows.
Forms.Button();
this.ServerAddress = new System.Windows.
Forms.TextBox();
this.Filename = new System.Windows.
Forms.TextBox();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.
Point(16, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.
Size(80, 23);
this.label1.TabIndex = 0;
this.label1.Text = "服務(wù)器地址:";
this.label1.TextAlign = System.Drawing.
ContentAlignment.MiddleRight;
//
// label2
//
this.label2.Location = new System.Drawing.
Point(16, 64);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.
Size(80, 23);
this.label2.TabIndex = 1;
this.label2.Text = "本地文件名:";
this.label2.TextAlign = System.Drawing.
ContentAlignment.MiddleRight;
//
// Download
//
this.Download.Location = new System.
Drawing.Point(288, 24);
this.Download.Name = "Download";
this.Download.TabIndex = 2;
this.Download.Text = "開始下載";
this.Download.Click += new System.
EventHandler(this.Download_Click);
//
// ServerAddress
//
this.ServerAddress.Location = new System.
Drawing.Point(96, 24);
this.ServerAddress.Name = "ServerAddress";
this.ServerAddress.Size = new System.
Drawing.Size(176, 21);
this.ServerAddress.TabIndex = 3;
this.ServerAddress.Text = "";
//
// Filename
//
this.Filename.Location = new System.
Drawing.Point(96, 64);
this.Filename.Name = "Filename";
this.Filename.Size = new System.
Drawing.Size(176, 21);
this.Filename.TabIndex = 4;
this.Filename.Text = "";
//
// Form1
//
this.AutoScaleBaseSize = new System.
Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.
Size(376, 117);
this.Controls.AddRange(new System.Windows.
Forms.Control[] {
this.Filename,
this.ServerAddress,
this.Download,
this.label2,
this.label1});
this.Name = "Form1";
this.Text = "網(wǎng)頁下載器";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 應(yīng)用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private string DoSocketGet(string server)
{
//定義一些必要的變量以及一條要發(fā)送到服務(wù)器的字符串
Encoding ASCII = Encoding.ASCII;
string Get = "GET / HTTP/1.1\r\nHost: "
+server+"\r\nConnection: Close\r\n\r\n";
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
String strRetPage = null;
//獲取服務(wù)器相關(guān)的IP地址列表,其中第一項即為我們所需的
IPAddress hostadd = Dns.Resolve(server).
AddressList[0];
//根據(jù)獲得的服務(wù)器的IP地址創(chuàng)建一個終結(jié)點,端口為默認的80
IPEndPoint EPhost = new IPEndPoint
(hostadd, 80);
//創(chuàng)建一個Socket實例
Socket s = new Socket(AddressFamily.
InterNetwork, SocketType.Stream,
ProtocolType.Tcp );
try
{
//用上面所取得的終結(jié)點連接到服務(wù)器
s.Connect(EPhost);
}
catch(Exception se)
{
MessageBox.Show("連接錯誤:"+se.
Message,"提示信息",MessageBoxButtons.
RetryCancel,MessageBoxIcon.Information);
}
if (!s.Connected)
{
strRetPage = "不能連接到服務(wù)器!";
return strRetPage;
}
try
{
//向服務(wù)器發(fā)送GET命令
s.Send(ByteGet, ByteGet.Length,
SocketFlags.None);
}
catch(Exception ce)
{
MessageBox.Show("發(fā)送錯誤:"+ce.
Message,"提示信息",MessageBoxButtons.
RetryCancel,MessageBoxIcon.Information);
}
//接收頁面數(shù)據(jù),直到所有字節(jié)接收完畢
Int32 bytes = s.Receive(RecvBytes,
RecvBytes.Length, 0);
strRetPage = "以下是在服務(wù)器" + server +
"上的默認網(wǎng)頁:\r\n";
strRetPage = strRetPage + ASCII.GetString
(RecvBytes, 0, bytes);
while (bytes > 0)
{
bytes = s.Receive(RecvBytes,
RecvBytes.Length, SocketFlags.None);
strRetPage = strRetPage + ASCII.
GetString(RecvBytes, 0, bytes);
}
//禁用并關(guān)閉Socket實例
s.Shutdown(SocketShutdown.Both);
s.Close();
return strRetPage;
}
private void Download_Click(object sender, System.
EventArgs e)
{
//將所讀取的字符串轉(zhuǎn)換為字節(jié)數(shù)組
byte[] content=Encoding.ASCII.GetBytes
(DoSocketGet(ServerAddress.Text));
try
{
//創(chuàng)建文件流對象實例
FileStream fs=new FileStream
(Filename.Text,FileMode.OpenOrCreate,FileAccess.
ReadWrite);
//寫入文件
fs.Write(content,0,content.Length);
}
catch(Exception fe)
{
MessageBox.Show("文件創(chuàng)建/寫入錯誤:
"+fe.Message,"提示信息",MessageBoxButtons.
RetryCancel,MessageBoxIcon.Information);
}
}
}
}
其中主要的函數(shù)為DoSocketGet(),首先程序在響應(yīng)"開始下載"的事件處理函數(shù)Download_Click(),調(diào)用DoSocketGet()函數(shù),該函數(shù)完成了套接字的創(chuàng)建、連接、與主機的通訊-即獲得主機上的網(wǎng)頁、禁用、關(guān)閉等功能。在調(diào)用完DoSocketGet()函數(shù)后,Download_Click()函數(shù)創(chuàng)建一個FileStream對象,并試圖將DoSocketGet()函數(shù)返回的網(wǎng)頁文件以字節(jié)數(shù)組的形式寫到本機文件中,最終形成在本機上的一個Html文件,這樣就完成了一個網(wǎng)頁文件的下載工作了。
不過這個程序的功能比較簡單,不能作為真正的網(wǎng)頁瀏覽器用,網(wǎng)頁文件下載后還是要用IE等瀏覽器才能打開。然而作為一個解釋.NET底層網(wǎng)絡(luò)編程的實例絕對是一個好例子,所以希望讀者能好好研究,同時讀者還可以添加文件下載進度條等以完善本程序。
注:以上程序在Windows 2000服務(wù)器版、Visual Studio.Net中文正式版下調(diào)試通過