三.网页下载器实例介绍:
最后,我就综合以上.NET网络编程的一些知识,向大家展示一个很好的实例。该实例是一个运用Socket的基于同步模式的客户端应用程序,它首先通过解析服务器的IP地址建立一个终结点,同时创建一个基于流套接字的Socket连接,其运用的协议是TCP协议。通过该Socket就可以发送获取网页的命令,再通过该Socket获得服务器上默认的网页,最后通过文件流将获得的数据写入本机文件。这样就完成了网页的下载工作了,程序运行的效果如下所示:
程序的代码如下:
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();
&nbs"