三.网页下载器实例介绍:
最后,我就综合以上.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();
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
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器