程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#網絡編程概述(3)

C#網絡編程概述(3)

編輯:C#入門知識

最後,我就綜合以上C#網絡編程的一些知識,向大家展示一個很好的實例。該實例是一個運用Socket的基於同步模式的客戶端應用程序,它首先通過解析服務器的IP地址建立一個終結點,同時創建一個基於流套接字的Socket連接,其運用的協議是TCP協議。通過該Socket就可以發送獲取網頁的命令,再通過該Socket獲得服務器上默認的網頁,最後通過文件流將獲得的數據寫入本機文件。這樣就完成了網頁的下載工作了,程序運行的效果如下所示:

源代碼如下:(其中主要的函數為DoSocketGet())

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

{

///

/// Form1 的摘要說明。

///

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;

///

/// 必需的設計器變量。

///

private System.ComponentModel.Container components = null;

public Form1()

{

//

// Windows 窗體設計器支持所必需的

//

InitializeComponent();

//

// TODO: 在 InitializeComponent 調用後添加任何構造函數代碼

//

}

///

/// 清理所有正在使用的資源。

///

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows Form Designer generated code

///

/// 設計器支持所需的方法 - 不要使用代碼編輯器修改

/// 此方法的內容。

///

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 = "服務器地址:";

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 = "網頁下載器";

this.ResumeLayout(false);


}

#endregion

///

/// 應用程序的主入口點。

///

[STAThread]

static void Main()

{

Application.Run(new Form1());

}

private string DoSocketGet(string server)

{

file://定義一些必要的變量以及一條要發送到服務器的字符串

Encoding ASCII = Encoding.ASCII;

string Get = "GET / HTTP/1.1 Host: " + server +

" Connection: Close ";

Byte[] ByteGet = ASCII.GetBytes(Get);

Byte[] RecvBytes = new Byte[256];

String strRetPage = null;

file://獲取服務器相關的IP地址列表,其中第一項即為我們所需的

IPAddress hostadd = Dns.Resolve(server).AddressList[0];

file://根據獲得的服務器的IP地址創建一個終結點,端口為默認的80

IPEndPoint EPhost = new IPEndPoint(hostadd, 80);

file://創建一個Socket實例

Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

ProtocolType.Tcp );


try

{

file://用上面所取得的終結點連接到服務器

s.Connect(EPhost);

}

catch(Exception se)

{

MessageBox.Show("連接錯誤:"+se.Message,"提示信息",

MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);

}


if (!s.Connected)

{

strRetPage = "不能連接到服務器!";

return strRetPage;

}


try

{

file://向服務器發送GET命令

s.Send(ByteGet, ByteGet.Length, SocketFlags.None);

}

catch(Exception ce)

{

MessageBox.Show("發送錯誤:"+ce.Message,"提示信息",

MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);

}


file://接收頁面數據,直到所有字節接收完畢

Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);

strRetPage = "以下是在服務器" + server + "上的默認網頁: ";

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);

}

file://禁用並關閉Socket實例

s.Shutdown(SocketShutdown.Both);

s.Close();

 

return strRetPage;

}

private void Download_Click(object sender, System.EventArgs e)

{

file://將所讀取的字符串轉換為字節數組

byte[] content=Encoding.ASCII.GetBytes(DoSocketGet(ServerAddress.Text));

try

{

file://創

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved