《设计模式》实验指导书08版(20xx

时间:2024.4.8

《设计模式》实验指导书

实验学时:16学时

20##-10-08
Netbeans 6.7.1安装说明

由于NetBeans 6.7.1是NetBeans平台中支持UML插件最好的,所以本实现选择该平台作为开发工具。

从“http://netbeans.org/downloads/6.7.1/index.html”可下载NetBeans 6.7.1,如图1,建议选择第三列232MB的安装包下载netbeans-6.7.1-ml-java-windows.exe。

图1 下载窗口

向下滚动窗口,如图2,点击“ZIP文件格式”超链接,可进入与平台无关的模块下载页面,如图3所示。

图2 下载窗口下部

在模块集群部分选择下载“netbeans-6.7.1-200911211148-ml-uml.zip”,得到UML插件的本地安装程序。

图3 平台无关的ZIP文件

安装NetBeans过程中,注意选择定制安装,不安装服务器产品。解压上述ZIP文件到本地,可以得到一个uml6文件夹。把该文件夹复制到NetBeans的安装目录下,启动NetBeans后,选择“文件-新建项目”,有如图4所示的窗口,可发现UML模块已经可用,选择UML即可建立UML项目。

图4 新建项目窗口

在类别窗口选择UML,在项目窗口选择“Java平台模型”,即可建立UML项目。同样在类别窗口选择“Java”,在项目窗口选择“Java应用程序”,即可建立一个Java控制台应用项目。

右键点击UML项目,选择“生成代码”,选择目标项目,即可在目标项目中产生Java代码,非常方便,如图5所示。

图5 基于UML插件生成Java代码


实验一、单例模式(2学时)

【实验目的】

1、了解单例模式的应用场景、目的和解决问题的方法。

2、掌握单例模式的结构、各角色之间的协作过程和代码实现。

3、了解单例模式的应用。

【实验性质】

验证性实验

【实验内容与步骤】

1、试用Java或C#语言,以多种方式实现单例模式,调试运行你的程序,并对各种方式进行评价。

2、选择1题中某一种形式的例子加以改造,使其至多能够产生4个不同实例。

【实验作业】

1、单例模式的目的是什么?试用UML图表示单例模式的结构,并指明单例模式所涉及的角色、各角色的功能以及角色之间的协作关系。

2、客户端如何使用单例模式(即客户程序如何调用单例模式模块创建对象)?

3、寻找一个简单的连接池组件,试分析单例模式在其中的应用(选作)。


实验二、抽象工厂模式(4学时)

【实验目的】

1、了解抽象工厂模式的应用场景、目的和解决问题的方法。

2、掌握抽象工厂模式的结构、各角色之间的协作过程和代码实现。

3、了解抽象工厂模式的应用。

【实验性质】

验证性实验

【实验内容与步骤】

1、试用Java或C#语言实现抽象工厂模式的结构,并用代码说明客户端程序如何应用抽象工厂模式。

2、某地区的农产品市场分南方市场和北方市场,分别销售南方和北方的农产品。其中农产品设计水果和素菜两大类,而水果有北方水果(如梨子)和南方水果(如香蕉)之分,蔬菜有北方素菜(如大蒜)和南方蔬菜(如黄瓜)之分。现有客户购买梨子、香蕉各五十斤,大蒜和黄瓜各二十斤,请用代码模拟。

【实验作业】

1、谈谈你对产品族、产品等级等概念的理解和认识。

2、试用UML图表示抽象工厂模式的结构,并指明模式所涉及的角色、角色的功能以及各角色之间的协作关系。

3、抽象工厂模式、工厂方法模式以及简单工厂模式之间有什么区别和联系?各用在什么场景下?

4、谈谈你对创建型模式的认识。


实验三、适配器模式(4学时)

【实验目的】

1、了解适配器模式的应用场景、目的和解决问题的方法。

2、掌握适配器模式的结构、各角色之间的协作过程和代码实现。

3、了解适配器模式的应用。

【实验性质】

综合性实验

【实验内容与步骤】

1、试用Java或C#语言实现适配器模式的结构,并用代码说明客户端程序如何应用适配器模式。

2、考虑Cat和Dog两类对象,都有叫、跑、睡觉\抓老鼠等功能。现在客户要用Cat抓老鼠,但客户没有Cat,只好求Dog帮忙,请用适配器模式模拟本例。

3、JTable是Swing中用表格形式显示数据的组件,由于不同客户对数据的管理要求是不同,JTable使用了适配器模式。其中核心类有TableModel和AbstractTableModel。JTable用TableModel 接口提供的方法访问表格数据。为方便编程,AbstractTableModel实现了TableModel大部分接口,客户只需实现AbstractTableModel即可。请用UML图分析Jtable的这种实现机制,并举例说明Jtable的使用方法。

4、窗口(Windows)程序需要处理各种各样的事件,Java Swing的事件处理机制涉及三个角色:事件源(在该组件上产生了某种动作或事件)、事件(是什么样的事件,鼠标移动事件?键盘点击事件?对应java.util.EventObject)和事件监听者(该类实现对动作或事件的响应,对应java.util.EventListener)。

要使事件源A对事件B做C类型的处理,需要自定义事件监听类、给事件源(组件)注册监听:

A.AddCListener(Bevent  event)

如果事件很多,则需要编写的监听类也很多。请查阅资料,以例分析Java应用事件适配器来处理这个问题的机制,并上机实验。

【实验作业】

1、适配器模式的目的是什么?类适配器与对象适配器模式的区别是什么?

2、试用UML图表示适配器模式的结构,并指明适配器模式中的角色、各角色的功能及其协作关系。


实验四、代理模式(2学时)

【实验目的】

1、了解代理模式的应用场景、目的和解决问题的方法。

2、掌握代理模式的结构、各角色之间的协作过程和代码实现。

3、了解远程代理模式的应用。

【实验性质】

验证性实验

【实验内容与步骤】

1、用Java或C#语言实现代理模式的结构,并用代码说明客户端程序如何应用代理模式。

2、验证Java RMI中远程代理模式的使用

注:

Java中的RMI(远程方法调用)允许客户对象访问远程对象,涉及如下概念:

(1)远程接口:声明远程对象向客户提供的方法,该接口必须实现java.rmi.Remote,且所有的方法必须被声明为抛出java.rmi.RemoteException异常;一个远程对象应该实现该接口。

(2)远程对象:具体实现远程接口中声明的方法,该对象要扩展java.rmi.UnicastRemoteObject;必须有一个没有参数的构造函数;必须部署在服务器上,服务器通过调用它的无参构造函数来创建远程对象的实例。

(3)客户:试图调用远程方法的应用对象,其必须知道远程对象的远程接口;通过对RMI注册表的搜索来查找远程对象。

(4)辅助机制RMI注册表:其提供对不同远程对象的存储管理。一个远程对象在注册表中用唯一一个名字来标示。

(5)存根编译器RMIC:为远程对象生成存根和骨架。

本地存放远程对象的存根类和远程对象接口,其中的存根类负责把对远程对象的方法调用发送到远程对象所在的服务器上。服务器上远程对象的骨架把接收到的远程调用转发给远程对象的实例,如图所示。

服务器端处理

RMI编程过程如下:

(1)准备服务器端程序

//远程接口

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface Rocket extends Remote  {

       void boost(double factor) throws RemoteException;

       double getApogee() throws RemoteException;

       double getPrice() throws RemoteException;

}

//远程对象

import java.rmi.*;

import java.rmi.server.UnicastRemoteObject;

import com.oozinoz.*;

public class RocketImpl extends UnicastRemoteObject

     implements Rocket{

   protected  double price;

   protected  double apogee;

  

   public  RocketImpl(double price,double apogee)

     throws RemoteException{

            this.price=price;

            this.apogee=apogee;

     }

    

     public void boost(double factor){

            apogee=factor;

     }

     public double getApogee(){

            return apogee;

     }

     public double getPrice(){

            return price;

     }

    

     public static void main (String[] args) {

            try{

                   Rocket biggie=new RocketImpl(29.5,820);

                     Naming.rebind("rmi://localhost:5000/Biggie",biggie);

                     System.out.println("远程对象biggie已经注册!");

           }catch(Exception ee){

                  ee.printStackTrace();

           }

     }

}

(2)编译上述程序,在服务器端当前目录下用RMIC工具生成远程对象的存根和骨架(JDK 1.6中骨架和存根合在一起)类

rmic  RocketImpl

(3)启动服务器端RMI监听端口

Start  rmiregistry 5000

(4)注册远程对象

Java RocketImpl

(5)客户端编程

import  java.rmi.*;

public class ShowRocketClient {

      

       public static void main(String[] args) {

              // TODO: Add your code here

              try{

                     Object obj=Naming.lookup("rmi://localhost:5000/Biggie");

                     Rocket biggie=(Rocket)obj;

                     System.out.println("Apogee is "+biggie.getApogee());

              }catch(Exception e){

                     System.out.println("Exception while lookup a rocket");

                     e.printStackTrace();

              }

       }    

}

(6)把服务器端Rocket和存根类复制到客户端的当前目录下,编译上程序。

(7)运行客户端程序

Java  ShowRocketClient

如果运行程序时涉及权限问题,则服务器端用可采用如下形式:

   Java –Djava.security.policy=java.policy  远程对象类名 注册表所在的远程主机的DNS或IP  监听端口

(java.policy如下:

grant

{

        permission java.net.SocketPermission "*:1024-65535",

          "connect,accept,resolve";

        permission java.net.SocketPermission "*:1-1023",

          "connect,resolve";

           permission java.io.FilePermission "c:\\dp\\Proxy\\server\\*", "read,write";

};

客户端调用可采用如下形式:

Java –Djava.security.policy=java.policy  客户端类名 注册表所在的远程主机的DNS或IP  监听端口

(java.policy如下:

grant

{

       

        permission java.net.SocketPermission "*:1024-65535",

          "connect,accept,resolve";

        permission java.net.SocketPermission "*:1-1023",

          "connect,resolve";

};

【实验作业】

1、代理模式的目的是什么?使用在什么场景下?试用UML图表示代理模式的结构,并指明代理模式中的角色、各角色的功能及其协作关系。

2、结构型模式有什么特点?

3、Java使用流的机制来实现输入/输出。流是数据的有序排列,从流源出发,到流到某个目的地。流分输入流和输出流。应用程序从输入流读取数据,向输出流写数据。如应用程序使用FileInputStream从磁盘读取数据,用FileOutputStream向磁盘写数据。可以使用数组、String、File作为流源,也可以用一个已经存在的流作流源。Java的流具有对称性:

输入-输出对称:InputStream与OutputStram负责Byte流的输入与输出;Reader与Writer负责Char流的输入与输出。

Byte-Char对称:InputStream和Reader的子类分别负责Byte和Char流的输入;OutputStram和Writer分别负责Byte和Char流的输出。

Java使用装饰模式对一些流处理器做装饰,以改进性能或功能。如通过装饰Inputstream,得到具有特定功能的新流,如DataInputStream、BufferedInputStream、LineNumberInputStream、PushbackInputStream(注:这些类的基类都是FilterInputStram)。通过装饰OutputStream,得到新流DataOutputStream、PrintStream、BufferedOutputStream。

此外,Java在实现一些流处理器时,使用了装饰模式。如FileInputStream继承InputStream,引用FileDiscriptor对象,把FileDiscriptor对象适配成InputStream对象。

依据上述背景介绍,查阅资料,从适配器模式和装饰模式分析Java IO类的设计机制(最好找到JDK的源码,通过分析源码,画UML图来分析)。


 实验五、观测者模式(4学时)

【实验目的】

1、了解观测者模式的应用场景、目的和解决问题的方法。

2、掌握观测者模式的结构、各角色之间的协作过程和代码实现。

3、了解观测者模式的应用。

【实验性质】

验证性实验

【实验内容与步骤】

1、用Java或C#语言实现观测者模式的结构,并用代码说明客户端程序如何应用观测者模式。

2、请用观测者模式实现一个汽车驾驶室仪表系统,当汽车改变速度、改变方向时实时显示汽车的速度、方向、指示灯等信息。

3、从观测者模式的角度剖析并应用java.awt.image.ImageObserver。

【实验作业】

1、试用UML图表示观测者模式的结构,并指明观测者模式的角色、各角色的功能及其协作关系,并谈谈你对观测者模式的理解。

2、查阅资料,以例说明Java或C#对观测者模式的支持(如java.util.Observable)

3、行为型模式有何特点?


第二篇:《网络程序设计实验指导书》20xx版


《网络程序设计》实验指导书

一、课程名称与大纲依据

课程名称:网络程序设计

依据:    网络程序设计T课程教学大纲

二、实验性质与类别

性质:操作、程序设计类实验

类别:应用、技能训练实验

三、实验教学安排

学时:26学时

四、实验目的要求

实验教学是《网络程序设计》课程教学的一个必要组成部分,不属于单独的实验课程。通过理论教学和实验等环节的教学,使学生加深对教学内容的理解与认识,培养学生的网络程序设计、调试和动态页面制作的能力。

五、实验内容

实验一、委托与事件... 1

实验二、控件应用... 3

实验三、ADO.NET编程... 3

实验四、实现tcp点对点通信、udp点对点、组播的步骤和程序基本架构... 3

实验五、编程实现FTP、SMTP、POP3通信的基本步骤和程序框架... 30

实验六、GDI+的应用... 68

实验七、基于组件的开发技术... 68

实验八、web service的开发与应用... 68

实验一、委托与事件

       实验目的:了解委托与事件的基本概念,学习使用委托与事件进行简单的程序开发

       实验内容与步骤:

1.  声明一个委托类型和一个事件

2.编写调用事件的方法

3.编写事件的处理方法

4.将事件和委托关联

5.编写主程序验证

       参考代码:

       using System;

namespace MyCollections

{

       using System.Collections;

       public delegate void ChangedEventHandler(object sender, EventArgs e);

       public class ListWithChangedEvent: ArrayList

       {

              public event ChangedEventHandler Changed;

              protected virtual void OnChanged(EventArgs e)

              {

                     if (Changed != null)

                            Changed(this, e);

              }

              public override int Add(object value)

              {

                     int i = base.Add(value);

                     OnChanged(EventArgs.Empty);

                     return i;

              }

              public override void Clear()

              {

                     base.Clear();

                     OnChanged(EventArgs.Empty);

              }

              public override object this[int index]

              {

                     set

                     {

                            base[index] = value;

                            OnChanged(EventArgs.Empty);

                     }

              }

       }

}

namespace TestEvents

{

       using MyCollections;

       class EventListener

       {

              private ListWithChangedEvent List;

              public EventListener(ListWithChangedEvent list)

              {

                     List = list;

                     List.Changed += new ChangedEventHandler(ListChanged);

              }

              private void ListChanged(object sender, EventArgs e)

              {

                     Console.WriteLine("开始让我处理了!");

              }

              public void Detach()

              {

                     List.Changed -= new ChangedEventHandler(ListChanged);

                     List = null;

              }

       }

       class Test

       {

              public static void Main()

              {

                     ListWithChangedEvent list = new ListWithChangedEvent();

                     EventListener listener = new EventListener(list);

                     list.Add("item 1");

                     list.Clear();

                     listener.Detach();

                     Console.Read();

              }

       }

}

实验二、控件应用

实验目的:熟悉C#.NET的winform窗体控件和WEB控件的使用

        实验要求:

1、winform窗体控件使用:

设计一个winform窗体,包括mainmenu控件、textbox控件、tooltip控件、tabcontrol控件、listview控件,并编写相应的事件响应代码

2、简单网页:

设计一个网页,包括button控件、textbox控件、panel控件、listbox控件、dropdownlist控件、image控件、hyperlink控件、table控件、marquee控件、embed控件、iframe控件、弹出对话框、验证控件,并编写相应的响应代码。

实验三、ADO.NET编程

        实验目的:学习数据库联接,了解sqldataadapter和sqldatareader工作原理

        实验内容与要求:

           1、 编程联接数据库,在winform上显示sqlserver2000中的pubs数据库的authers的内容,利用水晶报表把显示的内容生成报表;比较sqldataadapter和sqldatareader的区别。

           2、自建用自动增量做主码的数据表,使用dataset和datagrid在网页中分页显示表中的数据;然后

a)  使用交互方式在dataset中添加十条记录,并显示在datagrid中;

b)  再删去3条,并显示在datagrid中;

c)  再增加2条,并显示在datagrid中;

d)  再使用dataset修改数据表。


实验四、实现tcp点对点通信、udp点对点、组播的步骤和程序基本架构

实验目的:实现tcp点对点通信、udp点对点、组播的步骤和程序基本架构

实验内容与要求:

        阅读和调试完成下列参考程序;修改UDP点对点程序使它能进行在广域网中两局域网(10.1.1.*和11.1.1.*)之间进行点对点通信。网络拓扑图如下,其中ip:10.1.1.*,11.1.1.* 为局域网地址,

1、开发tcp同步和异步套接字点对点通信程序

//服务器端

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.Threading;

namespace TestSyncServer

{

     /// <summary>

     /// Form1 的摘要说明。

     /// </summary>

     public class Form1 : System.Windows.Forms.Form

     {

         private Socket socket;

         private Socket clientSocket;

         Thread thread;

         private System.Windows.Forms.Label label1;

         private System.Windows.Forms.Label label2;

         private System.Windows.Forms.Label label3;

         private System.Windows.Forms.Label label4;

         private System.Windows.Forms.GroupBox groupBox1;

         private System.Windows.Forms.TextBox textBoxIP;

         private System.Windows.Forms.TextBox textBoxPort;

         private System.Windows.Forms.Button buttonStart;

         private System.Windows.Forms.Button buttonSend;

         private System.Windows.Forms.Button buttonStop;

         private System.Windows.Forms.ListBox listBoxState;

         private System.Windows.Forms.RichTextBox richTextBoxAccept;

         private System.Windows.Forms.RichTextBox richTextBoxSend;

         /// <summary>

         /// 必需的设计器变量。

         /// </summary>

         private System.ComponentModel.Container components = null;

         public Form1()

         {

              //

              // Windows 窗体设计器支持所必需的

              //

              InitializeComponent();

              //

              // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

              //

              this.listBoxState.Items.Clear();

              this.richTextBoxAccept.Text="";

              this.richTextBoxSend.Text="";

         }

         /// <summary>

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

         /// </summary>

         protected override void Dispose( bool disposing )

         {

              if( disposing )

              {

                   if (components != null)

                   {

                       components.Dispose();

                   }

              }

              base.Dispose( disposing );

         }

         #region Windows 窗体设计器生成的代码

         /// <summary>

         /// 设计器支持所需的方法 - 不要使用代码编辑器修改

         /// 此方法的内容。

         /// </summary>

         private void InitializeComponent()

         {

              this.label1 = new System.Windows.Forms.Label();

              this.label2 = new System.Windows.Forms.Label();

              this.label3 = new System.Windows.Forms.Label();

              this.label4 = new System.Windows.Forms.Label();

              this.groupBox1 = new System.Windows.Forms.GroupBox();

              this.listBoxState = new System.Windows.Forms.ListBox();

              this.textBoxIP = new System.Windows.Forms.TextBox();

              this.textBoxPort = new System.Windows.Forms.TextBox();

              this.buttonStart = new System.Windows.Forms.Button();

              this.buttonSend = new System.Windows.Forms.Button();

              this.buttonStop = new System.Windows.Forms.Button();

              this.richTextBoxAccept = new System.Windows.Forms.RichTextBox();

              this.richTextBoxSend = new System.Windows.Forms.RichTextBox();

              this.groupBox1.SuspendLayout();

              this.SuspendLayout();

              //

              // label1

              //

              this.label1.Location = new System.Drawing.Point(8, 32);

              this.label1.Name = "label1";

              this.label1.Size = new System.Drawing.Size(56, 23);

              this.label1.TabIndex = 0;

              this.label1.Text = "服务器IP";

              //

              // label2

              //

              this.label2.Location = new System.Drawing.Point(8, 72);

              this.label2.Name = "label2";

              this.label2.Size = new System.Drawing.Size(56, 23);

              this.label2.TabIndex = 0;

              this.label2.Text = "监听端口";

              //

              // label3

              //

              this.label3.Location = new System.Drawing.Point(8, 136);

              this.label3.Name = "label3";

              this.label3.Size = new System.Drawing.Size(56, 23);

              this.label3.TabIndex = 0;

              this.label3.Text = "接收信息";

              //

              // label4

              //

              this.label4.Location = new System.Drawing.Point(8, 224);

              this.label4.Name = "label4";

              this.label4.Size = new System.Drawing.Size(56, 23);

              this.label4.TabIndex = 0;

              this.label4.Text = "发送信息";

              //

              // groupBox1

              //

              this.groupBox1.Controls.Add(this.listBoxState);

              this.groupBox1.Location = new System.Drawing.Point(216, 16);

              this.groupBox1.Name = "groupBox1";

              this.groupBox1.TabIndex = 1;

              this.groupBox1.TabStop = false;

              this.groupBox1.Text = "服务器状态";

              //

              // listBoxState

              //

              this.listBoxState.ItemHeight = 12;

              this.listBoxState.Location = new System.Drawing.Point(8, 16);

              this.listBoxState.Name = "listBoxState";

              this.listBoxState.Size = new System.Drawing.Size(184, 76);

              this.listBoxState.TabIndex = 0;

              //

              // textBoxIP

              //

              this.textBoxIP.Location = new System.Drawing.Point(72, 32);

              this.textBoxIP.Name = "textBoxIP";

              this.textBoxIP.ReadOnly = true;

              this.textBoxIP.Size = new System.Drawing.Size(128, 21);

              this.textBoxIP.TabIndex = 2;

              this.textBoxIP.Text = "127.0.0.1";

              //

              // textBoxPort

              //

              this.textBoxPort.Location = new System.Drawing.Point(72, 72);

              this.textBoxPort.Name = "textBoxPort";

              this.textBoxPort.ReadOnly = true;

              this.textBoxPort.TabIndex = 3;

              this.textBoxPort.Text = "6788";

              //

              // buttonStart

              //

              this.buttonStart.Location = new System.Drawing.Point(56, 320);

              this.buttonStart.Name = "buttonStart";

              this.buttonStart.TabIndex = 5;

              this.buttonStart.Text = "开始监听";

              this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);

              //

              // buttonSend

              //

              this.buttonSend.Location = new System.Drawing.Point(168, 320);

              this.buttonSend.Name = "buttonSend";

              this.buttonSend.TabIndex = 5;

              this.buttonSend.Text = "发送信息";

              this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);

              //

              // buttonStop

              //

              this.buttonStop.Location = new System.Drawing.Point(288, 320);

              this.buttonStop.Name = "buttonStop";

              this.buttonStop.TabIndex = 5;

              this.buttonStop.Text = "停止监听";

              this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);

              //

              // richTextBoxAccept

              //

              this.richTextBoxAccept.Location = new System.Drawing.Point(72, 120);

              this.richTextBoxAccept.Name = "richTextBoxAccept";

              this.richTextBoxAccept.Size = new System.Drawing.Size(344, 96);

              this.richTextBoxAccept.TabIndex = 6;

              this.richTextBoxAccept.Text = "richTextBoxAccept";

              //

              // richTextBoxSend

              //

              this.richTextBoxSend.Location = new System.Drawing.Point(72, 224);

              this.richTextBoxSend.Name = "richTextBoxSend";

              this.richTextBoxSend.Size = new System.Drawing.Size(344, 80);

              this.richTextBoxSend.TabIndex = 6;

              this.richTextBoxSend.Text = "richTextBoxSend";

              //

              // Form1

              //

              this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

              this.ClientSize = new System.Drawing.Size(432, 349);

              this.Controls.Add(this.richTextBoxAccept);

              this.Controls.Add(this.buttonStart);

              this.Controls.Add(this.textBoxPort);

              this.Controls.Add(this.textBoxIP);

              this.Controls.Add(this.groupBox1);

              this.Controls.Add(this.label1);

              this.Controls.Add(this.label2);

              this.Controls.Add(this.label3);

              this.Controls.Add(this.label4);

              this.Controls.Add(this.buttonSend);

              this.Controls.Add(this.buttonStop);

              this.Controls.Add(this.richTextBoxSend);

              this.Name = "Form1";

              this.Text = "服务器";

              this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);

              this.Load += new System.EventHandler(this.Form1_Load);

              this.groupBox1.ResumeLayout(false);

              this.ResumeLayout(false);

         }

         #endregion

         /// <summary>

         /// 应用程序的主入口点。

         /// </summary>

         [STAThread]

         static void Main()

         {

              Application.Run(new Form1());

         }

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

         {

              this.buttonStart.Enabled=false;

              IPAddress ip=IPAddress.Parse(this.textBoxIP.Text);

              IPEndPoint server=new IPEndPoint(ip,Int32.Parse(this.textBoxPort.Text));

              socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

              socket.Bind(server);

              //监听客户端连接

              socket.Listen(10);

              clientSocket=socket.Accept();

              //显示客户IP和端口号

this.listBoxState.Items.Add("与客户 "+clientSocket.RemoteEndPoint.ToString()+" 建立连接");

              //创建一个线程接收客户信息

              thread=new Thread(new ThreadStart(AcceptMessage));

              thread.Start();

         }

         private void AcceptMessage()

         {

              while(true)

              {

                   try

                   {

                       NetworkStream netStream=new NetworkStream(clientSocket);

                       byte[] datasize=new byte[4];

                       netStream.Read(datasize,0,4);

                       int size=System.BitConverter.ToInt32(datasize,0);

                       Byte[] message=new byte[size];

                       int dataleft=size;

                       int start=0;

                       //while(dataleft>0)

                       {

                            int recv=netStream.Read(message,start,dataleft);

                            //start+=recv;

                            //dataleft-=recv;

                       }

                       //string gg;

                       //gg=message.ToString();

                       this.richTextBoxAccept.Rtf=System.Text.Encoding.Unicode.GetString(datasize);

                   }

                   catch

                   {

                       this.listBoxState.Items.Add("与客户断开连接");

                       break;

                   }

              }

         }

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

         {

              string str=this.richTextBoxSend.Rtf;

              int i=str.Length;

              if(i==0)

              {

                   return;

              }

              else

              {

                    //因为str为Unicode编码,每个字符占2字节,所以实际字节数应*2

                   i*=2;

              }

              byte[] datasize=new byte[4];

               //将32位整数值转换为字节数组

              datasize=System.BitConverter.GetBytes(i);

              byte[] sendbytes=System.Text.Encoding.Unicode.GetBytes(str);

              try

              {

                   NetworkStream netStream=new NetworkStream(clientSocket);

                   netStream.Write(datasize,0,4);

                   netStream.Write(sendbytes,0,sendbytes.Length);

                   netStream.Flush();

                   this.richTextBoxSend.Rtf="";

              }

              catch

              {

                   MessageBox.Show("无法发送!");

              }

         }

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

         {

              this.buttonStart.Enabled=true;

              try

              {

                   socket.Shutdown(SocketShutdown.Both);

                   socket.Close();

                   if(clientSocket.Connected)

                   {

                       clientSocket.Close();

                       thread.Abort();

                   }

              }

              catch

              {

                   MessageBox.Show("监听尚未开始,关闭无效!");

              }

         }

         private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

         {

              try

              {

                   socket.Shutdown(SocketShutdown.Both);

                   socket.Close();

                   if(clientSocket.Connected)

                   {

                       clientSocket.Close();

                       thread.Abort();

                   }

              }

              catch

              {}

         }

        

     }

}

//客户端

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.Threading;

using System.Runtime.Serialization.Formatters.Binary;

using System.Runtime.Serialization;

namespace TestSyncClient

{

       /// <summary>

       /// Form1 的摘要说明。

       /// </summary>

       public class Form1 : System.Windows.Forms.Form

       {

              private Socket socket;

              private Thread thread;

         public static int fs=0;

              private System.Windows.Forms.Label label1;

              private System.Windows.Forms.Label label2;

              private System.Windows.Forms.Label label3;

              private System.Windows.Forms.Label label4;

              private System.Windows.Forms.GroupBox groupBox1;

              private System.Windows.Forms.TextBox textBoxIP;

              private System.Windows.Forms.TextBox textBoxPort;

              private System.Windows.Forms.Button buttonRequest;

              private System.Windows.Forms.Button buttonSend;

              private System.Windows.Forms.Button buttonClose;

              private System.Windows.Forms.ListBox listBoxState;

              private System.Windows.Forms.RichTextBox richTextBoxSend;

              private System.Windows.Forms.RichTextBox richTextBoxReceive;

              private System.Windows.Forms.Button button1;

              private System.Windows.Forms.TextBox textBox1;

              /// <summary>

              /// 必需的设计器变量。

              /// </summary>

              private System.ComponentModel.Container components = null;

              public Form1()

              {

                     //

                     // Windows 窗体设计器支持所必需的

                     //

                     InitializeComponent();

                     //

                     // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

                     //

                     this.richTextBoxSend.Text="";

                     this.richTextBoxReceive.Text="";

                     this.listBoxState.Items.Clear();

                     this.textBox1.Text=fs.ToString();

              }

              /// <summary>

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

              /// </summary>

              protected override void Dispose( bool disposing )

              {

                     if( disposing )

                     {

                            if (components != null)

                            {

                                   components.Dispose();

                            }

                     }

                     base.Dispose( disposing );

              }

              #region Windows 窗体设计器生成的代码

              /// <summary>

              /// 设计器支持所需的方法 - 不要使用代码编辑器修改

              /// 此方法的内容。

              /// </summary>

              private void InitializeComponent()

              {

                     this.label1 = new System.Windows.Forms.Label();

                     this.label2 = new System.Windows.Forms.Label();

                     this.label3 = new System.Windows.Forms.Label();

                     this.label4 = new System.Windows.Forms.Label();

                     this.groupBox1 = new System.Windows.Forms.GroupBox();

                     this.listBoxState = new System.Windows.Forms.ListBox();

                     this.textBoxIP = new System.Windows.Forms.TextBox();

                     this.textBoxPort = new System.Windows.Forms.TextBox();

                     this.buttonRequest = new System.Windows.Forms.Button();

                     this.buttonSend = new System.Windows.Forms.Button();

                     this.buttonClose = new System.Windows.Forms.Button();

                     this.richTextBoxSend = new System.Windows.Forms.RichTextBox();

                     this.richTextBoxReceive = new System.Windows.Forms.RichTextBox();

                     this.button1 = new System.Windows.Forms.Button();

                     this.textBox1 = new System.Windows.Forms.TextBox();

                     this.groupBox1.SuspendLayout();

                     this.SuspendLayout();

                     //

                     // label1

                     //

                     this.label1.Location = new System.Drawing.Point(11, 31);

                     this.label1.Name = "label1";

                     this.label1.Size = new System.Drawing.Size(85, 29);

                     this.label1.TabIndex = 0;

                     this.label1.Text = "服务器IP";

                     //

                     // label2

                     //

                     this.label2.Location = new System.Drawing.Point(11, 93);

                     this.label2.Name = "label2";

                     this.label2.Size = new System.Drawing.Size(85, 29);

                     this.label2.TabIndex = 0;

                     this.label2.Text = "请求端口";

                     //

                     // label3

                     //

                     this.label3.Location = new System.Drawing.Point(11, 154);

                     this.label3.Name = "label3";

                     this.label3.Size = new System.Drawing.Size(85, 30);

                     this.label3.TabIndex = 0;

                     this.label3.Text = "接收信息";

                     //

                     // label4

                     //

                     this.label4.Location = new System.Drawing.Point(11, 267);

                     this.label4.Name = "label4";

                     this.label4.Size = new System.Drawing.Size(85, 30);

                     this.label4.TabIndex = 0;

                     this.label4.Text = "发送信息";

                     //

                     // groupBox1

                     //

                     this.groupBox1.Controls.Add(this.listBoxState);

                     this.groupBox1.Location = new System.Drawing.Point(267, 10);

                     this.groupBox1.Name = "groupBox1";

                     this.groupBox1.Size = new System.Drawing.Size(266, 129);

                     this.groupBox1.TabIndex = 1;

                     this.groupBox1.TabStop = false;

                     this.groupBox1.Text = "程序状态";

                     //

                     // listBoxState

                     //

                     this.listBoxState.ItemHeight = 15;

                     this.listBoxState.Location = new System.Drawing.Point(11, 21);

                     this.listBoxState.Name = "listBoxState";

                     this.listBoxState.Size = new System.Drawing.Size(245, 79);

                     this.listBoxState.TabIndex = 0;

                     //

                     // textBoxIP

                     //

                     this.textBoxIP.Location = new System.Drawing.Point(107, 31);

                     this.textBoxIP.Name = "textBoxIP";

                     this.textBoxIP.ReadOnly = true;

                     this.textBoxIP.Size = new System.Drawing.Size(133, 25);

                     this.textBoxIP.TabIndex = 2;

                     this.textBoxIP.Text = "127.0.0.1";

                     //

                     // textBoxPort

                     //

                     this.textBoxPort.Location = new System.Drawing.Point(107, 93);

                     this.textBoxPort.Name = "textBoxPort";

                     this.textBoxPort.ReadOnly = true;

                     this.textBoxPort.Size = new System.Drawing.Size(133, 25);

                     this.textBoxPort.TabIndex = 2;

                     this.textBoxPort.Text = "6788";

                     //

                     // buttonRequest

                     //

                     this.buttonRequest.Location = new System.Drawing.Point(64, 381);

                     this.buttonRequest.Name = "buttonRequest";

                     this.buttonRequest.Size = new System.Drawing.Size(100, 29);

                     this.buttonRequest.TabIndex = 3;

                     this.buttonRequest.Text = "请求连接";

this.buttonRequest.Click += new System.EventHandler(this.buttonRequest_Click);

                     //

                     // buttonSend

                     //

                     this.buttonSend.Location = new System.Drawing.Point(213, 381);

                     this.buttonSend.Name = "buttonSend";

                     this.buttonSend.Size = new System.Drawing.Size(100, 29);

                     this.buttonSend.TabIndex = 3;

                     this.buttonSend.Text = "发送信息";

this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);

                     //

                     // buttonClose

                     //

                     this.buttonClose.Location = new System.Drawing.Point(363, 381);

                     this.buttonClose.Name = "buttonClose";

                     this.buttonClose.Size = new System.Drawing.Size(100, 29);

                     this.buttonClose.TabIndex = 3;

                     this.buttonClose.Text = "关闭连接";

       this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);

                     //

                     // richTextBoxSend

                     //

                     this.richTextBoxSend.Location = new System.Drawing.Point(107, 267);

                     this.richTextBoxSend.Name = "richTextBoxSend";

                     this.richTextBoxSend.Size = new System.Drawing.Size(426, 103);

                     this.richTextBoxSend.TabIndex = 5;

                     this.richTextBoxSend.Text = "richTextBoxSend";

                     //

                     // richTextBoxReceive

                     //

              this.richTextBoxReceive.Location = new System.Drawing.Point(107, 154);

                     this.richTextBoxReceive.Name = "richTextBoxReceive";

                     this.richTextBoxReceive.Size = new System.Drawing.Size(426, 103);

                     this.richTextBoxReceive.TabIndex = 5;

                     this.richTextBoxReceive.Text = "richTextBoxReceive";

                     //

                     // button1

                     //

                     this.button1.Location = new System.Drawing.Point(480, 384);

                     this.button1.Name = "button1";

                     this.button1.Size = new System.Drawing.Size(48, 24);

                     this.button1.TabIndex = 6;

                     this.button1.Text = "button1";

                     this.button1.Click += new System.EventHandler(this.button1_Click);

                     //

                     // textBox1

                     //

                     this.textBox1.Location = new System.Drawing.Point(32, 64);

                     this.textBox1.Name = "textBox1";

                     this.textBox1.TabIndex = 7;

                     this.textBox1.Text = "textBox1";

                     //

                     // Form1

                     //

                     this.AutoScaleBaseSize = new System.Drawing.Size(8, 18);

                     this.ClientSize = new System.Drawing.Size(554, 417);

                     this.Controls.Add(this.textBox1);

                     this.Controls.Add(this.button1);

                     this.Controls.Add(this.richTextBoxSend);

                     this.Controls.Add(this.buttonRequest);

                     this.Controls.Add(this.textBoxIP);

                     this.Controls.Add(this.groupBox1);

                     this.Controls.Add(this.label1);

                     this.Controls.Add(this.label2);

                     this.Controls.Add(this.label3);

                     this.Controls.Add(this.label4);

                     this.Controls.Add(this.textBoxPort);

                     this.Controls.Add(this.buttonSend);

                     this.Controls.Add(this.buttonClose);

                     this.Controls.Add(this.richTextBoxReceive);

                     this.Name = "Form1";

                     this.Text = "客户端";

this.Closing+=new system.ComponentModel.CancelEventHandler(this.Form1_Closing);

                     this.groupBox1.ResumeLayout(false);

                     this.ResumeLayout(false);

              }

              #endregion

              /// <summary>

              /// 应用程序的主入口点。

              /// </summary>

              [STAThread]

              static void Main()

              {

                     Application.Run(new Form1());

              }

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

              {

                     IPEndPoint server=new IPEndPoint(IPAddress.Parse("127.0.0.1"),6788);

socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                     try

                     {

                            socket.Connect(server);

                     }

                     catch

                     {

                            MessageBox.Show("与服务器连接失败!");

                            return;

                     }

                     this.buttonRequest.Enabled=false;

                     this.listBoxState.Items.Add("与服务器连接成功");

            NetworkStream netStream=new NetworkStream(socket);

                                  

                     Thread thread=new Thread(new ThreadStart(AcceptMessage));

                     thread.Start();

                     //

            

                     ///

              }

              private void AcceptMessage()

              {

                     while(true)

                     {

                            try

                            {

                                   NetworkStream netStream=new NetworkStream(socket);

                                   byte[] datasize=new byte[4];

                                   netStream.Read(datasize,0,4);

                                   int size=System.BitConverter.ToInt32(datasize,0);

                                   Byte[] message=new byte[size];

                                   int dataleft=size;

                                   int start=0;

                                   while(dataleft>0)

                                   {

                                          int recv=netStream.Read(message,start,dataleft);

                                          start+=recv;

                                          dataleft-=recv;

                                   }

                                   this.richTextBoxReceive.Rtf=System.Text.Encoding.Unicode.GetString(message);

                            }

                            catch

                            {

                                   this.listBoxState.Items.Add("服务器断开连接。");

                                   break;

                            }

                     }

              }

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

              {

                     try

                     {

                            socket.Shutdown(SocketShutdown.Both);

                            socket.Close();

                            this.listBoxState.Items.Add("与主机断开连接");

                            thread.Abort();

                     }

                     catch

                     {

                            MessageBox.Show("尚未与主机连接,断开无效!");

                     }

                     this.buttonRequest.Enabled=true;

              }

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

              {

                     string str=this.richTextBoxSend.Rtf;

                     int i=str.Length;

                     if(i==0)

                     {

                            return;

                     }

                     else

                     {

               //因为str为Unicode编码,每个字符占2字节,所以实际字节数应*2

                            i*=2;

                     }

                     byte[] datasize=new byte[4];

                     //将32位整数值转换为字节数组

                     datasize=System.BitConverter.GetBytes(i);

                     byte[] sendbytes=System.Text.Encoding.Unicode.GetBytes(str);

                     try

                     {

                            if(fs==0){

                 //datasize=System.BitConverter.GetBytes(i);

                                   NetworkStream netStream=new NetworkStream(socket);

                                   netStream.Write(fdatasize,0,4);

                                   netStream.Write(fsendbytes,0,fsendbytes.Length);

                                   netStream.Flush();

                                   this.richTextBoxSend.Text=fsendbytes.ToString();

                             fs=1;

                                   this.textBox1.Text=fs.ToString();

                            }

                            else

                            {

                                   fs=2;

                                   NetworkStream netStream=new NetworkStream(socket);

                                   netStream.Write(datasize,0,4);

                                   netStream.Write(sendbytes,0,sendbytes.Length);

                                   netStream.Flush();

                                   this.richTextBoxSend.Text="";

                                   this.textBox1.Text=fs.ToString();

                            }

                     }

                     catch

                     {

                            MessageBox.Show("无法发送!");

                     }

              }

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

              {

                     try

                     {

                            socket.Shutdown(SocketShutdown.Both);

                            socket.Close();

                     }

                     catch

                     {}

              }

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

              {

                     string str=this.richTextBoxSend.Rtf;

                     int i=str.Length;

                     if(i==0)

                     {

                            return;

                     }

                     else

                     {

                     //因为str为Unicode编码,每个字符占2字节,所以实际字节数应*2

                            i*=2;

                     }

                     byte[] datasize=new byte[4];

                     //将32位整数值转换为字节数组

                     datasize=System.BitConverter.GetBytes(i);

                     byte[] sendbytes=System.Text.Encoding.Unicode.GetBytes(str);

                     try

                     {

                            NetworkStream netStream=new NetworkStream(socket);

                            netStream.Write(datasize,0,4);

                            netStream.Write(sendbytes,0,sendbytes.Length);

                            netStream.Flush();

                            this.richTextBoxSend.Text="";

                     }

                     catch

                     {

                            MessageBox.Show("无法发送!");

                     }

              }

       }

}

        2、开发UDP点对点、组播程序

       //UDP点对点

       using System;

using System.Net;

using System.Net.Sockets;

class TestSimpleUdp

{

       public static void Main()

       {

              int length;

              byte[] bytes=new byte[1024];

              Socket socket=

                     new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);

              //参数1指定本机IP地址(此处指所有可用的IP地址),参数2指定接收用的端口

              IPEndPoint myHost=new IPEndPoint(IPAddress.Any,6789);

              //将本机IP地址和端口与套接字绑定,为接收做准备

              socket.Bind(myHost);

              //定义远程IP地址和端口(实际使用时应为远程主机IP地址),为发送数据做准备

              IPEndPoint remote=new IPEndPoint(IPAddress.Parse("127.0.0.1"),6789);

              //从IPEndPoint得到EndPoint类型

              EndPoint remoteHost=(EndPoint)remote;

              Console.Write("输入发送的信息:");

              string str=Console.ReadLine();

              //字符串转换为字节数组

              bytes=System.Text.Encoding.Unicode.GetBytes(str);

              //向远程终端发送信息

              socket.SendTo(bytes,bytes.Length,SocketFlags.None,remoteHost);

              while(true)

              {

                     Console.WriteLine("等待接收...");

                     //从本地绑定的IP地址和端口接收远程终端的数据,返回接收的字节数

                     length=socket.ReceiveFrom(bytes,ref remoteHost);

                     //字节数组转换为字符串

                     str=System.Text.Encoding.Unicode.GetString(bytes,0,length);

                     Console.WriteLine("接收到信息:{0}",str);

                     //如果收到的消息是"bye",则跳出给循环

                     if(str=="bye") break;

                     Console.Write("输入回送信息(bye退出):");

                     str=Console.ReadLine();

                     bytes=System.Text.Encoding.Unicode.GetBytes(str);

                     socket.SendTo(bytes,remoteHost);

              }

              //关闭套接字

              socket.Close();

              Console.WriteLine("对方已经byebye了,请按回车键结束。");

              Console.ReadLine();

       }

}

//UDP组播实现网络会议

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.Threading;

namespace EX11_9

{

       /// <summary>

       /// Form1 的摘要说明。

       /// </summary>

       public class Form1 : System.Windows.Forms.Form

       {

              Socket socket;

              Thread recvThread;

              IPAddress address=IPAddress.Parse("224.100.0.1");

              IPEndPoint multiIPEndPoint;

              private System.Windows.Forms.GroupBox groupBox1;

              private System.Windows.Forms.GroupBox groupBox2;

              private System.Windows.Forms.ListBox listBox1;

              private System.Windows.Forms.ListBox listBox2;

              private System.Windows.Forms.Label label1;

              private System.Windows.Forms.TextBox textBox1;

              /// <summary>

              /// 必需的设计器变量。

              /// </summary>

              private System.ComponentModel.Container components = null;

              public Form1()

              {

                     //

                     // Windows 窗体设计器支持所必需的

                     //

                     InitializeComponent();

                     //

                     // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

                     //

                     this.textBox1.Text="";

                     multiIPEndPoint=new IPEndPoint(address,6788);

socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);

                     IPEndPoint iep=new IPEndPoint(IPAddress.Any,6788);

                     EndPoint ep=(EndPoint)iep;

                     socket.Bind(ep);

                     socket.SetSocketOption(SocketOptionLevel.IP,

                            SocketOptionName.AddMembership,new MulticastOption(address));

                     recvThread=new Thread(new ThreadStart(ReceiveMessage));

                     //设置该线程在后台运行

                     recvThread.IsBackground=true;

                     recvThread.Start();

                     byte[] bytes=System.Text.Encoding.Unicode.GetBytes("#");

                     socket.SendTo(bytes,SocketFlags.None,multiIPEndPoint);

              }

              /// <summary>

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

              /// </summary>

              protected override void Dispose( bool disposing )

              {

                     if( disposing )

                     {

                            if (components != null)

                            {

                                   components.Dispose();

                            }

                     }

                     base.Dispose( disposing );

              }

              #region Windows 窗体设计器生成的代码

              /// <summary>

              /// 设计器支持所需的方法 - 不要使用代码编辑器修改

              /// 此方法的内容。

              /// </summary>

              private void InitializeComponent()

              {

                     this.groupBox1 = new System.Windows.Forms.GroupBox();

                     this.groupBox2 = new System.Windows.Forms.GroupBox();

                     this.listBox1 = new System.Windows.Forms.ListBox();

                     this.listBox2 = new System.Windows.Forms.ListBox();

                     this.label1 = new System.Windows.Forms.Label();

                     this.textBox1 = new System.Windows.Forms.TextBox();

                     this.groupBox2.SuspendLayout();

                     this.SuspendLayout();

                     //

                     // groupBox1

                     //

                     this.groupBox1.Location = new System.Drawing.Point(16, 24);

                     this.groupBox1.Name = "groupBox1";

                     this.groupBox1.Size = new System.Drawing.Size(296, 200);

                     this.groupBox1.TabIndex = 0;

                     this.groupBox1.TabStop = false;

                     this.groupBox1.Text = "讨论内容";

                     //

                     // groupBox2

                     //

                     this.groupBox2.Controls.Add(this.listBox2);

                     this.groupBox2.Location = new System.Drawing.Point(328, 24);

                     this.groupBox2.Name = "groupBox2";

                     this.groupBox2.Size = new System.Drawing.Size(224, 200);

                     this.groupBox2.TabIndex = 1;

                     this.groupBox2.TabStop = false;

                     this.groupBox2.Text = "参加讨论人员";

                     //

                     // listBox1

                     //

                     this.listBox1.ItemHeight = 12;

                     this.listBox1.Location = new System.Drawing.Point(32, 40);

                     this.listBox1.Name = "listBox1";

                     this.listBox1.Size = new System.Drawing.Size(264, 172);

                     this.listBox1.TabIndex = 2;

                     //

                     // listBox2

                     //

                     this.listBox2.ItemHeight = 12;

                     this.listBox2.Location = new System.Drawing.Point(8, 24);

                     this.listBox2.Name = "listBox2";

                     this.listBox2.Size = new System.Drawing.Size(208, 160);

                     this.listBox2.TabIndex = 3;

                     //

                     // label1

                     //

                     this.label1.Location = new System.Drawing.Point(48, 240);

                     this.label1.Name = "label1";

                     this.label1.Size = new System.Drawing.Size(32, 23);

                     this.label1.TabIndex = 3;

                     this.label1.Text = "发言";

                     //

                     // textBox1

                     //

                     this.textBox1.Location = new System.Drawing.Point(88, 240);

                     this.textBox1.Name = "textBox1";

                     this.textBox1.Size = new System.Drawing.Size(456, 21);

                     this.textBox1.TabIndex = 4;

                     this.textBox1.Text = "textBox1";

this.textBox1.KeyPress+=new system.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);

                     //

                     // Form1

                     //

                     this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

                     this.ClientSize = new System.Drawing.Size(584, 273);

                     this.Controls.Add(this.textBox1);

                     this.Controls.Add(this.label1);

                     this.Controls.Add(this.listBox1);

                     this.Controls.Add(this.groupBox2);

                     this.Controls.Add(this.groupBox1);

                     this.Name = "Form1";

                     this.Text = "Form1";

this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);

                     this.groupBox2.ResumeLayout(false);

                     this.ResumeLayout(false);

              }

              #endregion

              /// <summary>

              /// 应用程序的主入口点。

              /// </summary>

              [STAThread]

              static void Main()

              {

                     Application.Run(new Form1());

              }

              private void ReceiveMessage()

              {

                     EndPoint ep=(EndPoint)multiIPEndPoint;

                     byte[] bytes=new byte[1024];

                     string str;

                     int length;

                     while(true)

                     {

                            length=socket.ReceiveFrom(bytes,ref ep);

                            string epAddress=ep.ToString();

                            epAddress=epAddress.Substring(0,epAddress.LastIndexOf(":"));

                            str=System.Text.Encoding.Unicode.GetString(bytes,0,length);

                            switch(str[0])

                            {

                                   case '#':  //进入会议室

                                          this.listBox1.Items.Add("["+epAddress+"]进入。");

                                          string str1="&:"+epAddress;

                                          for(int i=0;i<this.listBox2.Items.Count;i++)

                                          {

                                                 str1+=":"+this.listBox2.Items[i].ToString();

                                          }

                                          byte[] users=System.Text.Encoding.Unicode.GetBytes(str1);

                                          socket.SendTo(users,SocketFlags.None,multiIPEndPoint);

                                          break;

                                   case '@': //退出会议室

                                          this.listBox1.Items.Add("["+epAddress+"]退出。");

                                          this.listBox2.Items.Remove(epAddress);

                                          break;

                                   case '&': //参加会议人员名单

                                          string[] strArray=str.Split(':');

                                          for(int i=1;i<strArray.Length;i++)

                                          {

                                                 bool isExist=false;

                                                 for(int j=0;j<this.listBox2.Items.Count;j++)

                                                 {

                                                        if(strArray[i]==this.listBox2.Items[j].ToString())

                                                        {

                                                               isExist=true;

                                                               break;

                                                        }

                                                 }

                                                 if(isExist==false)

                                                 {

                                                        this.listBox2.Items.Add(strArray[i]);

                                                 }

                                          }

                                          break;

                                   case '!':  //发言内容

                                          this.listBox1.Items.Add("["+epAddress+"]说:");

                                          this.listBox1.Items.Add(str.Substring(1));

                                          this.listBox1.SelectedIndex=this.listBox1.Items.Count-1;

                                          break;

                            }

                     }

              }

private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

              {

                     if(e.KeyChar==(char)Keys.Return)

                     {

                            if(this.textBox1.Text.Trim().Length>0)

                            {

                                   byte[] bytes=System.Text.Encoding.Unicode.GetBytes("!"+this.textBox1.Text);

                                   this.textBox1.Text="";

                                   socket.SendTo(bytes,SocketFlags.None,multiIPEndPoint);

                            }

                     }

              }

       private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

              {

                     byte[] bytes=System.Text.Encoding.Unicode.GetBytes("@");

                     socket.SendTo(bytes,SocketFlags.None,multiIPEndPoint);

                     recvThread.Abort();

                     socket.Close();

              }

       }

}


实验五、编程实现FTP、SMTP、POP3通信的基本步骤和程序框架

实验目的:编程实现FTP、SMTP、POP3通信的基本步骤和程序框架

       实验内容与要求:阅读和调试完成下列程序,了解如何配置路由器的nat协议才能使广域网中的客户端访问局域网中的FTP服务器,网络拓扑图如下:10.1.1.*,11.1.1.*是局域网地址

1、  开发FTP协议通信程序

//服务器端

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.Threading;

using System.IO;

namespace FTPServer

{

    /// <summary>

    /// Form1 的摘要说明。

    /// </summary>

    public class Form1 : System.Windows.Forms.Form

    {

           TcpListener myListener;

           private System.Windows.Forms.ListBox listBox1;

           private System.Windows.Forms.Button buttonStart;

           private System.Windows.Forms.Button buttonStop;

           private System.Windows.Forms.GroupBox groupBox1;

           private System.Windows.Forms.Label label1;

           private System.Windows.Forms.TextBox textBox1;

           /// <summary>

           /// 必需的设计器变量。

           /// </summary>

           private System.ComponentModel.Container components = null;

           public Form1()

           {

                  //

                  // Windows 窗体设计器支持所必需的

                  //

                  InitializeComponent();

                  //

                  // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

                  //

           }

           /// <summary>

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

           /// </summary>

           protected override void Dispose( bool disposing )

           {

                  if( disposing )

                  {

                         if (components != null)

                         {

                                components.Dispose();

                         }

                  }

                  base.Dispose( disposing );

           }

           #region Windows 窗体设计器生成的代码

           /// <summary>

           /// 设计器支持所需的方法 - 不要使用代码编辑器修改

           /// 此方法的内容。

           /// </summary>

           private void InitializeComponent()

           {

                  this.listBox1 = new System.Windows.Forms.ListBox();

                  this.buttonStart = new System.Windows.Forms.Button();

                  this.buttonStop = new System.Windows.Forms.Button();

                  this.groupBox1 = new System.Windows.Forms.GroupBox();

                  this.label1 = new System.Windows.Forms.Label();

                  this.textBox1 = new System.Windows.Forms.TextBox();

                  this.groupBox1.SuspendLayout();

                  this.SuspendLayout();

                  //

                  // listBox1

                  //

                  this.listBox1.ItemHeight = 12;

                  this.listBox1.Location = new System.Drawing.Point(24, 24);

                  this.listBox1.Name = "listBox1";

                  this.listBox1.Size = new System.Drawing.Size(368, 184);

                  this.listBox1.TabIndex = 0;

                  //

                  // buttonStart

                  //

                  this.buttonStart.Location = new System.Drawing.Point(256, 232);

                  this.buttonStart.Name = "buttonStart";

                  this.buttonStart.TabIndex = 1;

                  this.buttonStart.Text = "开始监听";

                  this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);

                  //

                  // buttonStop

                  //

                  this.buttonStop.Location = new System.Drawing.Point(352, 232);

                  this.buttonStop.Name = "buttonStop";

                  this.buttonStop.TabIndex = 1;

                  this.buttonStop.Text = "停止监听";

                  this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);

                  //

                  // groupBox1

                  //

                  this.groupBox1.Controls.Add(this.listBox1);

                  this.groupBox1.Location = new System.Drawing.Point(16, 8);

                  this.groupBox1.Name = "groupBox1";

                  this.groupBox1.Size = new System.Drawing.Size(408, 216);

                  this.groupBox1.TabIndex = 2;

                  this.groupBox1.TabStop = false;

                  this.groupBox1.Text = "传递情况";

                  //

                  // label1

                  //

                  this.label1.Location = new System.Drawing.Point(24, 232);

                  this.label1.Name = "label1";

                  this.label1.Size = new System.Drawing.Size(48, 23);

                  this.label1.TabIndex = 3;

                  this.label1.Text = "主目录";

                  this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;

                  //

                  // textBox1

                  //

                  this.textBox1.Location = new System.Drawing.Point(80, 232);

                  this.textBox1.Name = "textBox1";

                  this.textBox1.Size = new System.Drawing.Size(152, 21);

                  this.textBox1.TabIndex = 4;

                  this.textBox1.Text = "d:\\myftp";

                  //

                  // Form1

                  //

                  this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

                  this.ClientSize = new System.Drawing.Size(440, 261);

                  this.Controls.Add(this.textBox1);

                  this.Controls.Add(this.label1);

                  this.Controls.Add(this.groupBox1);

                  this.Controls.Add(this.buttonStart);

                  this.Controls.Add(this.buttonStop);

                  this.Name = "Form1";

                  this.Text = "FTPServer";

this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);

                  this.groupBox1.ResumeLayout(false);

                  this.ResumeLayout(false);

           }

           #endregion

           /// <summary>

           /// 应用程序的主入口点。

           /// </summary>

           [STAThread]

           static void Main()

           {

                  Application.Run(new Form1());

           }

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

           {

                  this.listBox1.Items.Add("开始监听……");

                  //端口号6788

                  myListener=new TcpListener(IPAddress.Parse("127.0.0.1"),21);

                  myListener.Start();

                  Thread myThread=new Thread(new ThreadStart(ReceiveData));

                  myThread.Start();

           }

           private void ReceiveData()

           {

                  TcpClient newClient;

                  while(true)

                  {

                         try

                         {

                                //等待用户进入

                                newClient=myListener.AcceptTcpClient();

                         }

                         catch

                         {

                                //当单击“停止监听”或者退出时AcceptTcpClient()会产生异常

                                myListener.Stop();

                                break;

                         }

                         Receive tp=new Receive(newClient,ref listBox1,ref textBox1);

                         Thread thread=new Thread(new ThreadStart(tp.processService));

                         thread.Start();

                  }

           }

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

           {

                  try

                  {

                         myListener.Stop();

                  }

                  catch

                  {}

           }

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

           {

                  buttonStop_Click(null,null);

           }

    }

    public class Receive

    {

           private TcpClient client;

           private ListBox listbox;

           private TextBox textbox;

           public Receive(TcpClient tcpclient,ref ListBox listbox,ref TextBox textbox)

           {

                  client=tcpclient;

                  this.listbox=listbox;

                  this.textbox=textbox;

           }

           public void processService()

           {

                  NetworkStream netStream=client.GetStream();

StreamReader sr=new StreamReader(netStream,System.Text.Encoding.Unicode);

StreamWriter sw=new StreamWriter(netStream,System.Text.Encoding.Unicode);

                  sw.WriteLine("220");

                  sw.Flush();

                  listbox.Items.Add("有用户连接,发送:220");

                  while(true)

                  {

                         string str="";

                         try

                         {

                                //当用户非正常断开连接时,可能会产生异常

                                str=sr.ReadLine();

                         }

                         catch

                         {

                                listbox.Items.Add("用户意外断开连接。");

                                break;

                         }

                         //当用户非正常断开连接时,即使不出现异常,接收字符串也会为null

                         if(str==null)

                         {

                                listbox.Items.Add("用户意外断开连接。");

                                break;

                         }

                         else

                         {

                                listbox.Items.Add("收到:"+str);

                         }

                         string command="";

                         string parameter="";

                         int index=str.IndexOf(" ");

                         if(index>-1)

                         {

                                command=str.Substring(0,index);

                                parameter=str.Substring(index+1);

                                //将用户发送的虚拟目录转换为实际目录

                                parameter=parameter.Replace("server:",textbox.Text);

                         }

                         else

                         {

                                command=str;

                         }

                         FileStream fs=null;

                         switch(command)

                         {

                                case "LIST":

                                       //LIST表示用户希望得到指定目录下的子目录列表

                                       string[] dir=Directory.GetDirectories(parameter);

                                       string sendstr="";

                                       for(int i=0;i<dir.Length;i++)

                                       {

                                              //将实际目录换为虚拟目录

                                              dir[i]=dir[i].Replace(textbox.Text,"server:");

                                              sendstr+=dir[i]+"@";

                                       }

                                       //去掉最后一个@

                                       if(sendstr.Length>0)

                                       {

                                              sendstr=sendstr.Substring(0,sendstr.Length-1);

                                       }

                                       // 发送125到用户,意思为服务器准备传送数据

                                       sw.WriteLine("125");

                                       sw.Flush();

                                       listbox.Items.Add("发送:125");

                                       //发送子目录到用户

                                       sw.WriteLine(sendstr);

                                       sw.Flush();

                                       listbox.Items.Add("发送目录名:"+sendstr);

                                       //得到文件列表

                                       string[] files=Directory.GetFiles(parameter);

                                       sendstr="";

                                       for(int i=0;i<files.Length;i++)

                                       {

                                              //将实际目录换为虚拟目录

                                              files[i]=files[i].Replace(textbox.Text,"server:");

                                              sendstr+=files[i]+"@";

                                       }

                                       //去掉最后一个@

                                       if(sendstr.Length>0)

                                       {

                                              sendstr=sendstr.Substring(0,sendstr.Length-1);

                                       }

                                       //发送文件名到用户

                                       sw.WriteLine(sendstr);

                                       sw.Flush();

                                       listbox.Items.Add("发送文件名:"+sendstr);

                                       break;

                                case "RETR":

                                       //下载文件

                                       try

                                       {

                                              //如果文件有问题,构造文件流会产生异常

           fs=new FileStream(parameter,FileMode.Open,FileAccess.Read);

                                       }

                                       catch

                                       {

                                              fs.Close();

                                              break;

                                       }

                                       // 发送150到用户,意思为服务器文件状态良好

                                       sw.WriteLine("150");

                                       sw.Flush();

                                       listbox.Items.Add("发送:150");

                                       //发送文件长度

                                       sw.WriteLine(fs.Length.ToString());

                                       sw.Flush();

                                       listbox.Items.Add("发送:"+fs.Length.ToString()+"字节");

                                       for(int i=0;i<fs.Length;i++)

                                       {

                                              netStream.WriteByte((byte)fs.ReadByte());

                                              netStream.Flush();

                                       }

                                       fs.Close();

                                       break;

                                case "QUIT":

                                       //关闭TCP连接并释放与其关联的所有资源

                                       client.Close();

                                       listbox.Items.Add("关闭与该用户的连接");

                                       return;

                         }

                  }

                  //关闭TCP连接并释放与其关联的所有资源

                  client.Close();

           }

    }

}

//客户端

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.Threading;

using System.IO;

namespace FTPClient

{

    /// <summary>

    /// Form1 的摘要说明。

    /// </summary>

    public class Form1 : System.Windows.Forms.Form

    {

           TcpClient client;

           NetworkStream netStream;

        StreamReader sr;

           StreamWriter sw;

           private System.Windows.Forms.Button buttonConnect;

           private System.Windows.Forms.Button buttonDisConnect;

           private System.Windows.Forms.ListBox listBoxFile;

           private System.Windows.Forms.ListBox listBoxDir;

           private System.Windows.Forms.ListBox listBoxInfo;

           private System.Windows.Forms.Button buttonUpDir;

           private System.Windows.Forms.GroupBox groupBoxDir;

           private System.Windows.Forms.Button buttonDownload;

           private System.Windows.Forms.ProgressBar progressBar1;

           private System.Windows.Forms.GroupBox groupBoxFile;

           private System.Windows.Forms.GroupBox groupBoxInfo;

           /// <summary>

           /// 必需的设计器变量。

           /// </summary>

           private System.ComponentModel.Container components = null;

           public Form1()

           {

                  //

                  // Windows 窗体设计器支持所必需的

                  //

                  InitializeComponent();

                  //

                  // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

                  //

                  this.buttonUpDir.Enabled=false;

           }

           /// <summary>

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

           /// </summary>

           protected override void Dispose( bool disposing )

           {

                  if( disposing )

                  {

                         if (components != null)

                         {

                                components.Dispose();

                         }

                  }

                  base.Dispose( disposing );

           }

           #region Windows 窗体设计器生成的代码

           /// <summary>

           /// 设计器支持所需的方法 - 不要使用代码编辑器修改

           /// 此方法的内容。

           /// </summary>

           private void InitializeComponent()

           {

                  this.buttonConnect = new System.Windows.Forms.Button();

                  this.buttonDisConnect = new System.Windows.Forms.Button();

                  this.listBoxFile = new System.Windows.Forms.ListBox();

                  this.groupBoxDir = new System.Windows.Forms.GroupBox();

                  this.listBoxDir = new System.Windows.Forms.ListBox();

                  this.buttonUpDir = new System.Windows.Forms.Button();

                  this.groupBoxFile = new System.Windows.Forms.GroupBox();

                  this.progressBar1 = new System.Windows.Forms.ProgressBar();

                  this.buttonDownload = new System.Windows.Forms.Button();

                  this.groupBoxInfo = new System.Windows.Forms.GroupBox();

                  this.listBoxInfo = new System.Windows.Forms.ListBox();

                  this.groupBoxDir.SuspendLayout();

                  this.groupBoxFile.SuspendLayout();

                  this.groupBoxInfo.SuspendLayout();

                  this.SuspendLayout();

                  //

                  // buttonConnect

                  //

                  this.buttonConnect.Location = new System.Drawing.Point(104, 8);

                  this.buttonConnect.Name = "buttonConnect";

                  this.buttonConnect.TabIndex = 0;

                  this.buttonConnect.Text = "建立连接";

                  this.buttonConnect.Click += new System.EventHandler(this.buttonConnect_Click);

                  //

                  // buttonDisConnect

                  //

                  this.buttonDisConnect.Location = new System.Drawing.Point(264, 8);

                  this.buttonDisConnect.Name = "buttonDisConnect";

                  this.buttonDisConnect.TabIndex = 0;

                  this.buttonDisConnect.Text = "关闭连接";

this.buttonDisConnect.Click += new System.EventHandler(this.buttonDisConnect_Click);

                  //

                  // listBoxFile

                  //

                  this.listBoxFile.ItemHeight = 12;

                  this.listBoxFile.Location = new System.Drawing.Point(16, 24);

                  this.listBoxFile.Name = "listBoxFile";

                  this.listBoxFile.Size = new System.Drawing.Size(200, 100);

                  this.listBoxFile.TabIndex = 1;

this.listBoxFile.SelectedIndexChanged+=new System.EventHandler(this.listBoxFile_SelectedIndexChanged);

                  //

                  // groupBoxDir

                  //

                  this.groupBoxDir.Controls.Add(this.listBoxDir);

                  this.groupBoxDir.Controls.Add(this.buttonUpDir);

                  this.groupBoxDir.Location = new System.Drawing.Point(16, 40);

                  this.groupBoxDir.Name = "groupBoxDir";

                  this.groupBoxDir.Size = new System.Drawing.Size(232, 200);

                  this.groupBoxDir.TabIndex = 4;

                  this.groupBoxDir.TabStop = false;

                  this.groupBoxDir.Text = "目录";

                  //

                  // listBoxDir

                  //

                  this.listBoxDir.ItemHeight = 12;

                  this.listBoxDir.Location = new System.Drawing.Point(16, 24);

                  this.listBoxDir.Name = "listBoxDir";

                  this.listBoxDir.Size = new System.Drawing.Size(200, 136);

                  this.listBoxDir.TabIndex = 1;

this.listBoxDir.SelectedIndexChanged += new System.EventHandler(this.listBoxDir_SelectedIndexChanged);

                  //

                  // buttonUpDir

                  //

                  this.buttonUpDir.Location = new System.Drawing.Point(72, 168);

                  this.buttonUpDir.Name = "buttonUpDir";

                  this.buttonUpDir.Size = new System.Drawing.Size(88, 23);

                  this.buttonUpDir.TabIndex = 7;

                  this.buttonUpDir.Text = "上层目录";

this.buttonUpDir.Click += new System.EventHandler(this.buttonUpDir_Click);

                  //

                  // groupBoxFile

                  //

                  this.groupBoxFile.Controls.Add(this.progressBar1);

                  this.groupBoxFile.Controls.Add(this.listBoxFile);

                  this.groupBoxFile.Controls.Add(this.buttonDownload);

                  this.groupBoxFile.Location = new System.Drawing.Point(256, 40);

                  this.groupBoxFile.Name = "groupBoxFile";

                  this.groupBoxFile.Size = new System.Drawing.Size(232, 200);

                  this.groupBoxFile.TabIndex = 5;

                  this.groupBoxFile.TabStop = false;

                  this.groupBoxFile.Text = "文件";

                  //

                  // progressBar1

                  //

                  this.progressBar1.Location = new System.Drawing.Point(16, 136);

                  this.progressBar1.Name = "progressBar1";

                  this.progressBar1.Size = new System.Drawing.Size(200, 23);

                  this.progressBar1.TabIndex = 8;

                  //

                  // buttonDownload

                  //

                  this.buttonDownload.Location = new System.Drawing.Point(80, 168);

                  this.buttonDownload.Name = "buttonDownload";

                  this.buttonDownload.Size = new System.Drawing.Size(64, 23);

                  this.buttonDownload.TabIndex = 7;

                  this.buttonDownload.Text = "下载";

this.buttonDownload.Click += new System.EventHandler(this.buttonDownload_Click);

                  //

                  // groupBoxInfo

                  //

                  this.groupBoxInfo.Controls.Add(this.listBoxInfo);

                  this.groupBoxInfo.Location = new System.Drawing.Point(16, 248);

                  this.groupBoxInfo.Name = "groupBoxInfo";

                  this.groupBoxInfo.Size = new System.Drawing.Size(472, 96);

                  this.groupBoxInfo.TabIndex = 6;

                  this.groupBoxInfo.TabStop = false;

                  this.groupBoxInfo.Text = "传递情况";

                  //

                  // listBoxInfo

                  //

                  this.listBoxInfo.ItemHeight = 12;

                  this.listBoxInfo.Location = new System.Drawing.Point(8, 16);

                  this.listBoxInfo.Name = "listBoxInfo";

                  this.listBoxInfo.Size = new System.Drawing.Size(448, 76);

                  this.listBoxInfo.TabIndex = 1;

                  //

                  // Form1

                  //

                  this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

                  this.ClientSize = new System.Drawing.Size(504, 349);

                  this.Controls.Add(this.groupBoxInfo);

                  this.Controls.Add(this.groupBoxFile);

                  this.Controls.Add(this.groupBoxDir);

                  this.Controls.Add(this.buttonConnect);

                  this.Controls.Add(this.buttonDisConnect);

                  this.Name = "Form1";

                  this.Text = "FTPClient";

                  this.groupBoxDir.ResumeLayout(false);

                  this.groupBoxFile.ResumeLayout(false);

                  this.groupBoxInfo.ResumeLayout(false);

                  this.ResumeLayout(false);

           }

           #endregion

           /// <summary>

           /// 应用程序的主入口点。

           /// </summary>

           [STAThread]

           static void Main()

           {

                  Application.Run(new Form1());

           }

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

           {

                  try

                  {

                         //与服务器建立连接

                         client=new TcpClient("127.0.0.1",21);

                  }

                  catch

                  {

                         MessageBox.Show("与服务器连接失败!");

                         return;

                  }

                  netStream=client.GetStream();

                  sr=new StreamReader(netStream,System.Text.Encoding.Unicode);

                  string str=sr.ReadLine();

                  this.listBoxInfo.Items.Add("收到:"+str);

                  sw=new StreamWriter(netStream,System.Text.Encoding.Unicode);

                  //获取FTP根目录下的子目录和文件列表

                  GetDirAndFiles(@"server:\");

           }

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

           {

                  string path=this.groupBoxDir.Text;

                  //找到最后一个\,截去\

                  path=path.Substring(0,path.LastIndexOf("\\"));

                  //再从右到左找一个\

                  int num=path.LastIndexOf("\\");

                  //截去\后面的子串

                  path=path.Substring(0,num+1);

                  GetDirAndFiles(path);

           }

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

           {

                  sw.WriteLine("QUIT");

                  sw.Flush();

                  this.listBoxInfo.Items.Add("发送:QUIT");

                  client.Close();

           }

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

           {

                  if(this.listBoxDir.SelectedIndex==-1)

                  {

                         //获取当前目录下的子目录和文件列表

                         GetDirAndFiles(this.groupBoxDir.Text);

                  }

                  else

                  {

                         //获取所选择目录下的子目录和文件列表

                         GetDirAndFiles(this.listBoxDir.SelectedItem.ToString());

                  }

           }

           private void GetDirAndFiles(string path)

           {

                  if(this.listBoxDir.SelectedIndex>-1)

                  {

                         this.groupBoxDir.Text=this.listBoxDir.SelectedItem.ToString();

                  }

                  else

                  {

                         this.groupBoxDir.Text=path;

                  }

                  //-------判断当前目录是否为虚拟根目录---------

                  if(path==@"server:\")

                  {

                         this.buttonUpDir.Enabled=false;

                  }

                  else

                  {

                         this.buttonUpDir.Enabled=true;

                  }

                  //获取目录和文件列表

                  sw.WriteLine("LIST "+path);

                  sw.Flush();

                  this.listBoxInfo.Items.Add("发送:LIST "+path);

                  this.listBoxInfo.SelectedIndex=this.listBoxInfo.Items.Count-1;

                  string str=sr.ReadLine();

                  this.listBoxInfo.Items.Add("收到:"+str);

                  this.listBoxInfo.SelectedIndex=this.listBoxInfo.Items.Count-1;

                  if(str=="125")  //表示服务器已经准备好数据,并开始传送

                  {

                         //获取子目录列表

                         this.listBoxDir.Items.Clear();

                         str=sr.ReadLine();

                         this.listBoxInfo.Items.Add("收到:"+str);

                         this.listBoxInfo.SelectedIndex=this.listBoxInfo.Items.Count-1;

                         string[] strarray;

                         //字符串长度为0,说明当前目录下没有子目录

                         if(str.Length>0)

                         {

                                strarray=str.Split('@');

                                for(int i=0;i<strarray.Length;i++)

                                {

                                       this.listBoxDir.Items.Add(strarray[i]+"\\");

                                }

                         }

                         //获取文件列表

                         this.listBoxFile.Items.Clear();

                         str=sr.ReadLine();

                         this.listBoxInfo.Items.Add("收到:"+str);

                         this.listBoxInfo.SelectedIndex=this.listBoxInfo.Items.Count-1;

                         //字符串长度为0,说明当前目录下没有文件

                         if(str.Length>0)

                         {

                                strarray=str.Split('@');

                                for(int i=0;i<strarray.Length;i++)

                                {

                                       this.listBoxFile.Items.Add(strarray[i]);

                                }

                         }

                         this.buttonDownload.Enabled=false;

                  }

           }

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

           {

                  SaveFileDialog myfile=new SaveFileDialog();

                  if(myfile.ShowDialog()==DialogResult.OK)

                  {

                         //重画窗体内的所有控件,使窗体显示完整

                         foreach(Control control in this.Controls)

                         {

                                control.Update();

                         }

                         //base.OnPaint(new PaintEventArgs(this.CreateGraphics(),this.ClientRectangle));

                         string path=this.listBoxFile.SelectedItem.ToString();

                         sw.WriteLine("RETR "+path);

                         sw.Flush();

                         this.listBoxInfo.Items.Add("发送:RETR "+path);

                         this.listBoxInfo.SelectedIndex=this.listBoxInfo.Items.Count-1;

                         string str=sr.ReadLine();

                         this.listBoxInfo.Items.Add("收到:"+str);

                         this.listBoxInfo.SelectedIndex=this.listBoxInfo.Items.Count-1;

                         if(str=="150")  //表示服务器文件状态良好

                         {

                                string str1=sr.ReadLine();

                                this.listBoxInfo.Items.Add("文件长度:"+str1+"字节");

                                this.listBoxInfo.SelectedIndex=this.listBoxInfo.Items.Count-1;

                                int length=Convert.ToInt32(str1);

                                this.progressBar1.Minimum=0;

                                this.progressBar1.Maximum=length;

FileStream fs=new FileStream(myfile.FileName,FileMode.Create,FileAccess.Write);

                                for(int i=0;i<length;i++)

                                {

                                       fs.WriteByte((byte)netStream.ReadByte());

                                       fs.Flush();

                                       this.progressBar1.Value=i;

                                }

                                fs.Close();

                                MessageBox.Show("下载完毕!");

                                this.progressBar1.Value=0;

                         }

                  }

           }

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

           {

                  if(this.listBoxFile.SelectedIndex==-1)

                  {

                         this.buttonDownload.Enabled=false;

                  }

                  else

                  {

                         this.buttonDownload.Enabled=true;

                  }

           }

    }

}

2、开发SMTP、POP3协议通信程序

//邮件发送

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.IO;

namespace book14_1

{

    /// <summary>

    /// Form1 的摘要说明。

    /// </summary>

    public class Form1 : System.Windows.Forms.Form

    {

           private System.Windows.Forms.Label labelSrv;

           private System.Windows.Forms.TextBox tBSrv;

           private System.Windows.Forms.TextBox tBpwd;

           private System.Windows.Forms.Label labelPwd;

           private System.Windows.Forms.TextBox tBUser;

           private System.Windows.Forms.Label labelUser;

           private System.Windows.Forms.Label labelSender;

           private System.Windows.Forms.TextBox tBSend;

           private System.Windows.Forms.Label labelRev;

           private System.Windows.Forms.TextBox tBRev;

           private System.Windows.Forms.TextBox tBSubject;

           private System.Windows.Forms.Label labelsubject;

           private System.Windows.Forms.Label labelText;

           private System.Windows.Forms.TextBox tBMailText;

           private System.Windows.Forms.Button button1;

           private System.Windows.Forms.Button buttonSend;

           private System.Windows.Forms.ProgressBar pb1;

           private System.Windows.Forms.Label labelp;

           private System.Windows.Forms.Label labelTxt;

           private System.Windows.Forms.Label labelMsg;

           private System.Windows.Forms.ListBox listBoxMsg;

           /// <summary>

           /// 必需的设计器变量。

           /// </summary>

           private System.ComponentModel.Container components = null;

           public Form1()

           {

                  //

                  // Windows 窗体设计器支持所必需的

                  //

                  InitializeComponent();

                  //

                  // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

                  //

           }

           /// <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>

           /// 设计器支持所需的方法 - 不要使用代码编辑器修改

           /// 此方法的内容。

           /// </summary>

           private void InitializeComponent()

           {

                  this.labelSrv = new System.Windows.Forms.Label();

                  this.tBSrv = new System.Windows.Forms.TextBox();

                  this.tBpwd = new System.Windows.Forms.TextBox();

                  this.labelPwd = new System.Windows.Forms.Label();

                  this.tBUser = new System.Windows.Forms.TextBox();

                  this.labelUser = new System.Windows.Forms.Label();

                  this.labelSender = new System.Windows.Forms.Label();

                  this.tBSend = new System.Windows.Forms.TextBox();

                  this.labelRev = new System.Windows.Forms.Label();

                  this.tBRev = new System.Windows.Forms.TextBox();

                  this.tBSubject = new System.Windows.Forms.TextBox();

                  this.labelsubject = new System.Windows.Forms.Label();

                  this.labelText = new System.Windows.Forms.Label();

                  this.tBMailText = new System.Windows.Forms.TextBox();

                  this.button1 = new System.Windows.Forms.Button();

                  this.buttonSend = new System.Windows.Forms.Button();

                  this.pb1 = new System.Windows.Forms.ProgressBar();

                  this.labelp = new System.Windows.Forms.Label();

                  this.labelTxt = new System.Windows.Forms.Label();

                  this.labelMsg = new System.Windows.Forms.Label();

                  this.listBoxMsg = new System.Windows.Forms.ListBox();

                  this.SuspendLayout();

                  //

                  // labelSrv

                  //

                  this.labelSrv.Location = new System.Drawing.Point(16, 8);

                  this.labelSrv.Name = "labelSrv";

                  this.labelSrv.Size = new System.Drawing.Size(96, 16);

                  this.labelSrv.TabIndex = 1;

                  this.labelSrv.Text = "SMTP服务器地址";

                  //

                  // tBSrv

                  //

                  this.tBSrv.Location = new System.Drawing.Point(112, 8);

                  this.tBSrv.Name = "tBSrv";

                  this.tBSrv.Size = new System.Drawing.Size(368, 21);

                  this.tBSrv.TabIndex = 2;

                  this.tBSrv.Text = "henu.edu.cn";

                  //

                  // tBpwd

                  //

                  this.tBpwd.Location = new System.Drawing.Point(272, 40);

                  this.tBpwd.Name = "tBpwd";

                  this.tBpwd.PasswordChar = '*';

                  this.tBpwd.Size = new System.Drawing.Size(104, 21);

                  this.tBpwd.TabIndex = 20;

                  this.tBpwd.Text = "";

                  //

                  // labelPwd

                  //

                  this.labelPwd.Location = new System.Drawing.Point(216, 48);

                  this.labelPwd.Name = "labelPwd";

                  this.labelPwd.Size = new System.Drawing.Size(56, 32);

                  this.labelPwd.TabIndex = 19;

                  this.labelPwd.Text = "口令";

                  //

                  // tBUser

                  //

                  this.tBUser.Location = new System.Drawing.Point(80, 40);

                  this.tBUser.Name = "tBUser";

                  this.tBUser.Size = new System.Drawing.Size(80, 21);

                  this.tBUser.TabIndex = 18;

                  this.tBUser.Text = "";

                  //

                  // labelUser

                  //

                  this.labelUser.Location = new System.Drawing.Point(16, 48);

                  this.labelUser.Name = "labelUser";

                  this.labelUser.Size = new System.Drawing.Size(48, 24);

                  this.labelUser.TabIndex = 17;

                  this.labelUser.Text = "用户名";

                  //

                  // labelSender

                  //

                  this.labelSender.Location = new System.Drawing.Point(16, 112);

                  this.labelSender.Name = "labelSender";

                  this.labelSender.Size = new System.Drawing.Size(48, 16);

                  this.labelSender.TabIndex = 23;

                  this.labelSender.Text = "发信人";

                  //

                  // tBSend

                  //

                  this.tBSend.Location = new System.Drawing.Point(56, 104);

                  this.tBSend.Name = "tBSend";

                  this.tBSend.Size = new System.Drawing.Size(192, 21);

                  this.tBSend.TabIndex = 24;

                  this.tBSend.Text = "";

                  //

                  // labelRev

                  //

                  this.labelRev.Location = new System.Drawing.Point(280, 112);

                  this.labelRev.Name = "labelRev";

                  this.labelRev.Size = new System.Drawing.Size(88, 24);

                  this.labelRev.TabIndex = 25;

                  this.labelRev.Text = "收信人";

                  //

                  // tBRev

                  //

                  this.tBRev.Location = new System.Drawing.Point(328, 104);

                  this.tBRev.Name = "tBRev";

                  this.tBRev.Size = new System.Drawing.Size(192, 21);

                  this.tBRev.TabIndex = 26;

                  this.tBRev.Text = "";

                  //

                  // tBSubject

                  //

                  this.tBSubject.Location = new System.Drawing.Point(64, 152);

                  this.tBSubject.Name = "tBSubject";

                  this.tBSubject.Size = new System.Drawing.Size(448, 21);

                  this.tBSubject.TabIndex = 28;

                  this.tBSubject.Text = "";

                  //

                  // labelsubject

                  //

                  this.labelsubject.Location = new System.Drawing.Point(16, 160);

                  this.labelsubject.Name = "labelsubject";

                  this.labelsubject.Size = new System.Drawing.Size(96, 32);

                  this.labelsubject.TabIndex = 27;

                  this.labelsubject.Text = "主题";

                  //

                  // labelText

                  //

                  this.labelText.Location = new System.Drawing.Point(16, 224);

                  this.labelText.Name = "labelText";

                  this.labelText.Size = new System.Drawing.Size(88, 24);

                  this.labelText.TabIndex = 29;

                  this.labelText.Text = "邮件内容";

                  //

                  // tBMailText

                  //

                  this.tBMailText.Location = new System.Drawing.Point(16, 216);

                  this.tBMailText.Multiline = true;

                  this.tBMailText.Name = "tBMailText";

                  this.tBMailText.ScrollBars = System.Windows.Forms.ScrollBars.Both;

                  this.tBMailText.Size = new System.Drawing.Size(496, 216);

                  this.tBMailText.TabIndex = 30;

                  this.tBMailText.Text = "";

                  //

                  // button1

                  //

                  this.button1.Enabled = false;

                  this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;

                  this.button1.Location = new System.Drawing.Point(-8, 88);

                  this.button1.Name = "button1";

                  this.button1.Size = new System.Drawing.Size(552, 8);

                  this.button1.TabIndex = 31;

                  //

                  // buttonSend

                  //

                  this.buttonSend.Location = new System.Drawing.Point(184, 448);

                  this.buttonSend.Name = "buttonSend";

                  this.buttonSend.Size = new System.Drawing.Size(128, 32);

                  this.buttonSend.TabIndex = 32;

                  this.buttonSend.Text = "邮件发送";

                  this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);

                  //

                  // pb1

                  //

                  this.pb1.Location = new System.Drawing.Point(120, 488);

                  this.pb1.Maximum = 16;

                  this.pb1.Name = "pb1";

                  this.pb1.Size = new System.Drawing.Size(384, 16);

                  this.pb1.TabIndex = 33;

                  this.pb1.Visible = false;

                  //

                  // labelp

                  //

                  this.labelp.Location = new System.Drawing.Point(16, 488);

                  this.labelp.Name = "labelp";

                  this.labelp.Size = new System.Drawing.Size(80, 16);

                  this.labelp.TabIndex = 34;

                  this.labelp.Text = "正在发送邮件";

                  this.labelp.Visible = false;

                  //

                  // labelTxt

                  //

                  this.labelTxt.Location = new System.Drawing.Point(16, 192);

                  this.labelTxt.Name = "labelTxt";

                  this.labelTxt.Size = new System.Drawing.Size(64, 16);

                  this.labelTxt.TabIndex = 35;

                  this.labelTxt.Text = "邮件内容";

                  //

                  // labelMsg

                  //

                  this.labelMsg.Location = new System.Drawing.Point(16, 536);

                  this.labelMsg.Name = "labelMsg";

                  this.labelMsg.Size = new System.Drawing.Size(80, 16);

                  this.labelMsg.TabIndex = 36;

                  this.labelMsg.Text = "信息查看";

                  //

                  // listBoxMsg

                  //

                  this.listBoxMsg.ItemHeight = 12;

                  this.listBoxMsg.Location = new System.Drawing.Point(120, 520);

                  this.listBoxMsg.Name = "listBoxMsg";

                  this.listBoxMsg.ScrollAlwaysVisible = true;

                  this.listBoxMsg.Size = new System.Drawing.Size(408, 64);

                  this.listBoxMsg.TabIndex = 37;

                  //

                  // Form1

                  //

                  this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

                  this.ClientSize = new System.Drawing.Size(544, 597);

                  this.Controls.AddRange(new System.Windows.Forms.Control[] {

                                                                                                                             this.listBoxMsg,

                                                                                                                             this.labelMsg,

                                                                                                                             this.labelTxt,

                                                                                                                             this.labelp,

                                                                                                                             this.pb1,

                                                                                                                             this.buttonSend,

                                                                                                                             this.button1,

                                                                                                                             this.tBMailText,

                                                                                                                             this.labelText,

                                                                                                                             this.tBSubject,

                                                                                                                             this.labelsubject,

                                                                                                                             this.tBRev,

                                                                                                                             this.labelRev,

                                                                                                                             this.tBSend,

                                                                                                                             this.labelSender,

                                                                                                                             this.tBpwd,

                                                                                                                             this.labelPwd,

                                                                                                                             this.tBUser,

                                                                                                                             this.labelUser,

                                                                                                                             this.tBSrv,

                                                                                                                             this.labelSrv});

                  this.MaximizeBox = false;

                  this.Name = "Form1";

                  this.Text = "邮件发送实例";

                  this.Load += new System.EventHandler(this.Form1_Load);

                  this.ResumeLayout(false);

           }

           #endregion

           /// <summary>

           /// 应用程序的主入口点。

           /// </summary>

           [STAThread]

           static void Main()

           {

                  Application.Run(new Form1());

           }

        TcpClient smtpSrv;

           NetworkStream netStrm;

           string CRLF="\r\n";

           private void WriteStream(string strCmd)

           {

            strCmd+=CRLF;

                  byte[] bw=System.Text.Encoding.Default.GetBytes(strCmd.ToCharArray ());

                  netStrm.Write (bw,0,bw.Length );

         }

          

           private string AuthStream(string strCmd)

           {

                  try

                  {

                         byte[] by=System.Text.Encoding.Default.GetBytes(strCmd.ToCharArray ());

                         strCmd=Convert.ToBase64String(by);

                  }

                  catch(Exception ex)

                  {

                         return ex.ToString();

                        

                  }

                  return strCmd;

           }

          

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

           {

                  listBoxMsg.Items.Clear();

                  try

                  {

                         string data;

                pb1.Visible=true;

                     labelp.Visible=true;

                         pb1.Value=0;

                smtpSrv=new TcpClient (tBSrv.Text,25);

                         netStrm=smtpSrv.GetStream ();

                         StreamReader rdStrm=new StreamReader(smtpSrv.GetStream());

                         WriteStream("EHLO Local");

                listBoxMsg.Items.Add(rdStrm.ReadLine());

                         pb1.Value++;

                         WriteStream("AUTH LOGIN");

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                         pb1.Value++;

                         data=tBUser.Text;

                         data=AuthStream(data);

                         WriteStream(data);

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                         pb1.Value++;

                         data=tBpwd.Text;

                         data=AuthStream(data);

                         WriteStream(data);

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                         pb1.Value++;

                         data="MAIL FROM: <"+tBSend.Text+">";

                         WriteStream(data);

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                         pb1.Value++;

                         data="RCPT TO:<"+tBRev.Text +">";

                         WriteStream(data);

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                      pb1.Value++;

                         WriteStream("DATA");

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                         pb1.Value++;

                         data="Date:"+DateTime.Now;

                         WriteStream(data);

                         pb1.Value++;

                         data="From:"+tBSend.Text;

                         WriteStream(data);

                         pb1.Value++;

                         data="TO:"+tBRev.Text;

                         WriteStream(data);

                         pb1.Value++;

                         data="SUBJECT:"+tBSubject.Text;

                         WriteStream(data);

                         pb1.Value++;

                         data="Reply-TO:"+tBSend.Text;

                         WriteStream(data);

                         pb1.Value++;

                         WriteStream("");

                         pb1.Value++;

                         WriteStream(tBMailText.Text);

                         pb1.Value++;

                         WriteStream(".");

                         pb1.Value++;

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                         WriteStream("QUIT");

                         pb1.Value++;

                         listBoxMsg.Items.Add(rdStrm.ReadLine());

                         netStrm.Close();

                         rdStrm.Close();

                         pb1.Visible=false;

                         labelp.Visible=false;

                         MessageBox.Show("邮件发送成功","成功");

                  }

                  catch (Exception ex)

                  {

                  MessageBox.Show(ex.ToString(),"操作错误!");

                  }

           }

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

           {

          

           }

    }

}

//邮件接收

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.IO;

namespace book14_2

{

    /// <summary>

    /// Form1 的摘要说明。

    /// </summary>

    public class Form1 : System.Windows.Forms.Form

    {

           private System.Windows.Forms.GroupBox groupBoxcon;

           private System.Windows.Forms.Label labelSrv;

           private System.Windows.Forms.TextBox tBSrv;

           private System.Windows.Forms.Label labelUser;

           private System.Windows.Forms.TextBox tBUser;

           private System.Windows.Forms.Label labelPwd;

           private System.Windows.Forms.TextBox tBPwd;

           private System.Windows.Forms.Button buttonCon;

           private System.Windows.Forms.Button buttonDiscon;

           private System.Windows.Forms.RichTextBox rTBText;

           private System.Windows.Forms.GroupBox groupBoxTxt;

           private System.Windows.Forms.GroupBox groupBoxOpe;

           private System.Windows.Forms.ListBox listBoxOpe;

           private System.Windows.Forms.Button buttonRead;

           private System.Windows.Forms.Button buttonDel;

           private System.Windows.Forms.GroupBox groupBoxStat;

           private System.Windows.Forms.ListBox listBoxStatus;

           /// <summary>

           /// 必需的设计器变量。

           /// </summary>

           private System.ComponentModel.Container components = null;

           public Form1()

           {

                  //

                  // Windows 窗体设计器支持所必需的

                  //

                  InitializeComponent();

                  //

                  // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

                  //

           }

           /// <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>

           /// 设计器支持所需的方法 - 不要使用代码编辑器修改

           /// 此方法的内容。

           /// </summary>

           private void InitializeComponent()

           {

                  this.groupBoxcon = new System.Windows.Forms.GroupBox();

                  this.buttonDiscon = new System.Windows.Forms.Button();

                  this.buttonCon = new System.Windows.Forms.Button();

                  this.tBPwd = new System.Windows.Forms.TextBox();

                  this.labelPwd = new System.Windows.Forms.Label();

                  this.tBUser = new System.Windows.Forms.TextBox();

                  this.labelUser = new System.Windows.Forms.Label();

                  this.tBSrv = new System.Windows.Forms.TextBox();

                  this.labelSrv = new System.Windows.Forms.Label();

                  this.groupBoxTxt = new System.Windows.Forms.GroupBox();

                  this.rTBText = new System.Windows.Forms.RichTextBox();

                  this.groupBoxOpe = new System.Windows.Forms.GroupBox();

                  this.buttonDel = new System.Windows.Forms.Button();

                  this.buttonRead = new System.Windows.Forms.Button();

                  this.listBoxOpe = new System.Windows.Forms.ListBox();

                  this.groupBoxStat = new System.Windows.Forms.GroupBox();

                  this.listBoxStatus = new System.Windows.Forms.ListBox();

                  this.groupBoxcon.SuspendLayout();

                  this.groupBoxTxt.SuspendLayout();

                  this.groupBoxOpe.SuspendLayout();

                  this.groupBoxStat.SuspendLayout();

                  this.SuspendLayout();

                  //

                  // groupBoxcon

                  //

                  this.groupBoxcon.Controls.AddRange(new System.Windows.Forms.Control[] {

                                                                                                                                                  this.buttonDiscon,

                                                                                                                                                  this.buttonCon,

                                                                                                                                                  this.tBPwd,

                                                                                                                                                 this.labelPwd,

                                                                                                                                                  this.tBUser,

                                                                                                                                                 this.labelUser,

                                                                                                                                                  this.tBSrv,

                                                                                                                                                  this.labelSrv});

                  this.groupBoxcon.Location = new System.Drawing.Point(8, 24);

                  this.groupBoxcon.Name = "groupBoxcon";

                  this.groupBoxcon.Size = new System.Drawing.Size(608, 120);

                  this.groupBoxcon.TabIndex = 0;

                  this.groupBoxcon.TabStop = false;

                  this.groupBoxcon.Text = "连接操作";

                  //

                  // buttonDiscon

                  //

                  this.buttonDiscon.Enabled = false;

                  this.buttonDiscon.Location = new System.Drawing.Point(496, 72);

                  this.buttonDiscon.Name = "buttonDiscon";

                  this.buttonDiscon.Size = new System.Drawing.Size(72, 24);

                  this.buttonDiscon.TabIndex = 7;

                  this.buttonDiscon.Text = "断开连接";

                  this.buttonDiscon.Click += new System.EventHandler(this.buttonDiscon_Click);

                  //

                  // buttonCon

                  //

                  this.buttonCon.Location = new System.Drawing.Point(496, 32);

                  this.buttonCon.Name = "buttonCon";

                  this.buttonCon.Size = new System.Drawing.Size(72, 24);

                  this.buttonCon.TabIndex = 6;

                  this.buttonCon.Text = "建立连接";

                  this.buttonCon.Click += new System.EventHandler(this.buttonCon_Click);

                  //

                  // tBPwd

                  //

                  this.tBPwd.Location = new System.Drawing.Point(136, 88);

                  this.tBPwd.Name = "tBPwd";

                  this.tBPwd.PasswordChar = '*';

                  this.tBPwd.Size = new System.Drawing.Size(304, 21);

                  this.tBPwd.TabIndex = 5;

                  this.tBPwd.Text = "";

                  //

                  // labelPwd

                  //

                  this.labelPwd.Location = new System.Drawing.Point(40, 88);

                  this.labelPwd.Name = "labelPwd";

                  this.labelPwd.Size = new System.Drawing.Size(32, 24);

                  this.labelPwd.TabIndex = 4;

                  this.labelPwd.Text = "密码";

                  //

                  // tBUser

                  //

                  this.tBUser.Location = new System.Drawing.Point(136, 56);

                  this.tBUser.Name = "tBUser";

                  this.tBUser.Size = new System.Drawing.Size(304, 21);

                  this.tBUser.TabIndex = 3;

                  this.tBUser.Text = "";

                  //

                  // labelUser

                  //

                  this.labelUser.Location = new System.Drawing.Point(40, 56);

                  this.labelUser.Name = "labelUser";

                  this.labelUser.Size = new System.Drawing.Size(48, 16);

                  this.labelUser.TabIndex = 2;

                  this.labelUser.Text = "用户名";

                  //

                  // tBSrv

                  //

                  this.tBSrv.Location = new System.Drawing.Point(136, 24);

                  this.tBSrv.Name = "tBSrv";

                  this.tBSrv.Size = new System.Drawing.Size(304, 21);

                  this.tBSrv.TabIndex = 1;

                  this.tBSrv.Text = "";

                  //

                  // labelSrv

                  //

                  this.labelSrv.Location = new System.Drawing.Point(40, 24);

                  this.labelSrv.Name = "labelSrv";

                  this.labelSrv.Size = new System.Drawing.Size(96, 24);

                  this.labelSrv.TabIndex = 0;

                  this.labelSrv.Text = "POP3邮件服务器";

                  //

                  // groupBoxTxt

                  //

                  this.groupBoxTxt.Controls.AddRange(new System.Windows.Forms.Control[] {

                                                                                                                                                  this.rTBText});

                  this.groupBoxTxt.Location = new System.Drawing.Point(8, 184);

                  this.groupBoxTxt.Name = "groupBoxTxt";

                  this.groupBoxTxt.Size = new System.Drawing.Size(456, 304);

                  this.groupBoxTxt.TabIndex = 1;

                  this.groupBoxTxt.TabStop = false;

                  this.groupBoxTxt.Text = "邮件内容";

                  //

                  // rTBText

                  //

                  this.rTBText.Location = new System.Drawing.Point(16, 24);

                  this.rTBText.Name = "rTBText";

                  this.rTBText.Size = new System.Drawing.Size(432, 272);

                  this.rTBText.TabIndex = 0;

                  this.rTBText.Text = "";

                  this.rTBText.TextChanged += new System.EventHandler(this.rTBText_TextChanged);

                  //

                  // groupBoxOpe

                  //

                  this.groupBoxOpe.Controls.AddRange(new System.Windows.Forms.Control[] {

                                                                                                                                                  this.buttonDel,

                                                                                                                                                  this.buttonRead,

                                                                                                                                                  this.listBoxOpe});

                  this.groupBoxOpe.Location = new System.Drawing.Point(464, 184);

                  this.groupBoxOpe.Name = "groupBoxOpe";

                  this.groupBoxOpe.Size = new System.Drawing.Size(160, 304);

                  this.groupBoxOpe.TabIndex = 2;

                  this.groupBoxOpe.TabStop = false;

                  this.groupBoxOpe.Text = "操作";

                  //

                  // buttonDel

                  //

                  this.buttonDel.Enabled = false;

                  this.buttonDel.Location = new System.Drawing.Point(88, 256);

                  this.buttonDel.Name = "buttonDel";

                  this.buttonDel.Size = new System.Drawing.Size(64, 32);

                  this.buttonDel.TabIndex = 2;

                  this.buttonDel.Text = "删除信件";

                  this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);

                  //

                  // buttonRead

                  //

                  this.buttonRead.Enabled = false;

                  this.buttonRead.Location = new System.Drawing.Point(16, 256);

                  this.buttonRead.Name = "buttonRead";

                  this.buttonRead.Size = new System.Drawing.Size(64, 32);

                  this.buttonRead.TabIndex = 1;

                  this.buttonRead.Text = "阅读信件";

                  this.buttonRead.Click += new System.EventHandler(this.buttonRead_Click);

                  //

                  // listBoxOpe

                  //

                  this.listBoxOpe.Enabled = false;

                  this.listBoxOpe.ItemHeight = 12;

                  this.listBoxOpe.Location = new System.Drawing.Point(8, 24);

                  this.listBoxOpe.Name = "listBoxOpe";

                  this.listBoxOpe.ScrollAlwaysVisible = true;

                  this.listBoxOpe.Size = new System.Drawing.Size(144, 208);

                  this.listBoxOpe.TabIndex = 0;

                  //

                  // groupBoxStat

                  //

                  this.groupBoxStat.Controls.AddRange(new System.Windows.Forms.Control[] {

                                                                                                                                                   this.listBoxStatus});

                  this.groupBoxStat.Location = new System.Drawing.Point(8, 496);

                  this.groupBoxStat.Name = "groupBoxStat";

                  this.groupBoxStat.Size = new System.Drawing.Size(616, 88);

                  this.groupBoxStat.TabIndex = 3;

                  this.groupBoxStat.TabStop = false;

                  this.groupBoxStat.Text = "状态";

                  //

                  // listBoxStatus

                  //

                  this.listBoxStatus.ItemHeight = 12;

                  this.listBoxStatus.Location = new System.Drawing.Point(8, 16);

                  this.listBoxStatus.Name = "listBoxStatus";

                  this.listBoxStatus.ScrollAlwaysVisible = true;

                  this.listBoxStatus.Size = new System.Drawing.Size(600, 64);

                  this.listBoxStatus.TabIndex = 17;

                  //

                  // Form1

                  //

                  this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

                  this.ClientSize = new System.Drawing.Size(632, 597);

                  this.Controls.AddRange(new System.Windows.Forms.Control[] {

                                                                                                                             this.groupBoxStat,

                                                                                                                             this.groupBoxOpe,

                                                                                                                             this.groupBoxTxt,

                                                                                                                             this.groupBoxcon});

                  this.MaximizeBox = false;

                  this.Name = "Form1";

                  this.Text = "邮件接收处理实例";

                  this.Load += new System.EventHandler(this.Form1_Load);

                  this.groupBoxcon.ResumeLayout(false);

                  this.groupBoxTxt.ResumeLayout(false);

                  this.groupBoxOpe.ResumeLayout(false);

                  this.groupBoxStat.ResumeLayout(false);

                  this.ResumeLayout(false);

           }

           #endregion

           /// <summary>

           /// 应用程序的主入口点。

           /// </summary>

           [STAThread]

           static void Main()

           {

                  Application.Run(new Form1());

           }

           public TcpClient Server;

           public NetworkStream NetStrm;

           public StreamReader  RdStrm;

           public string Data;

           public byte[] szData;

           public string CRLF = "\r\n";

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

           {

          

           }

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

           {

                  Server = new TcpClient(tBSrv.Text,110);                                                     

                 

                  try

                  {

                         NetStrm = Server.GetStream();

                         RdStrm= new StreamReader(Server.GetStream(),System.Text.Encoding.Default);

                         listBoxStatus.Items.Add(RdStrm.ReadLine());

                         Data = "USER "+ tBUser.Text+CRLF;                      

                         szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                         NetStrm.Write(szData,0,szData.Length);

                         listBoxStatus.Items.Add(RdStrm.ReadLine());

                         Data = "PASS "+ tBPwd.Text+CRLF;                      

                         szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                         NetStrm.Write(szData,0,szData.Length);

                         listBoxStatus.Items.Add(RdStrm.ReadLine());

                         Data = "STAT"+CRLF;                      

                         szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                         NetStrm.Write(szData,0,szData.Length);

                         string st=RdStrm.ReadLine();

                         listBoxStatus.Items.Add(st);

                         st=st.Substring (4,st.IndexOf(" ",5)-4);

                         int count=Int32.Parse(st);

                         if(count>0)

                         {

                                listBoxOpe.Enabled=true;

                                buttonRead.Enabled=true;

                                buttonDel.Enabled=true;

                                listBoxStatus.Items.Clear();

                             listBoxOpe.Items.Clear();

                                for(int i=0;i< count;i++)

                                  listBoxOpe.Items.Add("第"+(i+1)+"封邮件");

                                listBoxOpe.SelectedIndex=0;

                         }

                         else

                         {

                                groupBoxOpe.Text="信箱中没有邮件";

                                listBoxOpe.Enabled=false;

                                buttonRead.Enabled=false;

                                buttonDel.Enabled=false;

                         }

                         buttonCon.Enabled=false;

                         buttonDiscon.Enabled = true;

                        

                  }

                  catch(InvalidOperationException err)

                  {

                         listBoxStatus.Items.Add("Error: "+err.ToString());

                  }

           }

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

           {

                 

                  Data = "QUIT"+CRLF;                      

                  szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                  NetStrm.Write(szData,0,szData.Length);

                  listBoxStatus.Items.Add(RdStrm.ReadLine());

                  NetStrm.Close();

                  RdStrm.Close();

                  listBoxOpe.Items.Clear();

                  rTBText.Clear();

                  listBoxOpe.Enabled=false;

                  buttonRead.Enabled=false;

                  buttonDel.Enabled=false;

                  buttonCon.Enabled = true;

                  buttonDiscon.Enabled = false;

                 

           }

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

           {

                 

                  String szTemp;                                         

                  rTBText.Clear();

                  try

                  {

                         string st=listBoxOpe.SelectedItem.ToString();

                         st=   st.Substring (1,st.IndexOf("封")-1);

                         Data = "RETR "+st+CRLF;                       

                         szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                         NetStrm.Write(szData,0,szData.Length);                          

                         szTemp = RdStrm.ReadLine();

                         if(szTemp[0]!='-')

                         {

                                while(szTemp!=".")

                                {

                                    rTBText.Text +=szTemp+CRLF;

                                       szTemp = RdStrm.ReadLine();

                                }

                         }

                         else

                         {

                                listBoxStatus.Items.Add(szTemp);

                         }

                  }

                  catch(InvalidOperationException err)

                  {

                         listBoxStatus.Items.Add("Error: "+err.ToString());

                  }

           }

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

           {

                  String szTemp;      

                  rTBText.Clear();           

                  try

                  {

                         string st=listBoxOpe.SelectedItem.ToString();

                         st=   st.Substring (1,st.IndexOf("封")-1);

                         Data = "DELE "+ st+CRLF;                      

                         szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());

                         NetStrm.Write(szData,0,szData.Length);     

                         listBoxStatus.Items.Add(RdStrm.ReadLine());

                         int j=listBoxOpe.SelectedIndex;

                         listBoxOpe.Items.Remove(listBoxOpe.Items[j].ToString() );

                         MessageBox.Show("删除成功","操作成功");

                        

                  }

                  catch(InvalidOperationException err)

                  {

                         listBoxStatus.Items.Add("Error: "+err.ToString());

                  }

           }

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

           {

          

           }

    }

}

实验六、GDI+的应用

实验目的:学习WEB应用程序中画图和显示动画的基本方法

实验内容与要求

1、在WEB应用程序中画一条bezier曲线

2、设计10秒钟动画并在winform上显示

实验七、基于组件的开发技术

    实验目的:学习组件开发方法和过程,实现在windows应用程序和web应用程序 中调用组件。

        实验内容与要求:

1、编写调试一个组件程序和一个windows自定义控件,

     2、在windows应用程序中调用该组件和控件。

     3、在web应用程序中调用组件和控件。

实验八、web service的开发与应用

   实验目的:了解XML文档格式,web service的运行原理;学习web service的开发、应用方法与过程。

   实验内容与要求:

1、编写和调试一个web service程序

2、在windows应用程序中调用该web service

3、在web应用程序中调用该web service

4、在JAVA程序中调用该web service

 

六、实验指导书和实验参考书

   1.  刘瑞新. C#网络编程及应用  ,机械工业出版社,2005.07

   2.  秦学礼. Web应用程序设计技术--ASP.net,清华大学出版社,2006.04

3. 黎晓冬,王福水.精通ASP.NET编程.第一版,北京:科学出版社

4. 章立民.用实例学ASP.NET.第一版,北京:电子工业出版社

5. 李旭 ,顾青.Visual Basic.NET.第一版,北京:中国铁道出版社

更多相关推荐:
设计模式实验报告

设计模式实验指导书10学时教师张凯实验一工厂模式的应用实验目的1掌握工厂模式Factory的特点2分析具体问题使用工厂模式进行设计实验内容和要求有一个OEM制造商代理做HP笔记本电脑Laptop后来该制造商得到...

1099111130设计模式实验报告

哈尔滨工业大学华德应用技术学院实验报告课程名称软件设计模式系别计算机应用技术系专业软件工程学号1099111130姓名陈天任学期20xx年春季学期实验成绩计算机应用技术系监制123456789101112131...

设计模式实验报告

实验报告计算机科学与技术学院课程名称软件设计模式专业计算机科学与技术班级学号姓名实验一单例模式的应用1实验目的1掌握单例模式Singleton的特点2分析具体问题使用单例模式进行设计2实验内容和要求很多应用项目...

刘伟设计模式实验报告实验一

12实验1UML实验1实验学时2每组人数1实验类型31基础性2综合性3设计性4研究性实验要求11必修2选修3其它实验类别31基础2专业基础3专业4其它一实验目的1学会安装和使用建模工具PowerDesigner...

java设计模式实验报告

设计模式实验报告学院:学院专业:班姓名:学号:指导教师:一.实例实例:简单工厂模式使用简单工厂模式设计一个可以创建不同几何形状(圆形、方形和三角形等)的绘图工具,每个几何图形都要有绘制draw()和擦除eras…

设计模式上机实验二实验报告

设计模式实验二实验报告书专业班级软件0703学号3901070324姓名吉亚云指导老师刘伟时间20xx年4月24日中南大学软件学院1实验二设计模式上机实验二一实验目的使用PowerDesigner和任意一种面向...

UML实验报告书实验3 设计模式

淮海工学院计算机工程学院实验报告书课程名UML理论及实践题目正向工程班级学号20xx140093姓名薛慧君UML理论与实践实验报告一目的与要求1熟悉面向对象原则熟悉GoF中的模式2会初步使用设计模式解决实际问题...

综合实验2文档说明(DAO设计模式)

综合实验2一实验目的JSP的基本语法Servlet的重定向和请求转发的应用熟悉DAO设计模式的应用掌握访问数据库的方法熟悉JSPServletJavaBean的开发模式要求1该实验为第二次个综合性实验请同学们在...

UML 新编实验指导书(实验九 设计模式与业务建模)

天津理工大学华信软件学院实验指导书课程名称软件工程与UML数据建模适应课程19xx216天津理工大学华信软件学院2上机实验九UML设计模式一实验目的分析研究UML典型设计模式提高系统架构能力二实验内容1Hand...

云大设计模式实验2 观察者模式

实验报告课程设计模式实验学期20xx20xx学年第一学期任课教师专业学号姓名成绩实验2观察者模式1题目使用JAVA内置的观察者模式重新实现教材中的气象站2模式设计的UML类图3程序源代码1主题类WeatherD...

仲恺软件设计模式实验指导书

设计模式实验指导一实验目的使用合理的UML建模工具ROSE或者Visio和任意一种面向对象编程语言实现几种常用的设计模式加深对这些模式的理解包括简单工厂模式工厂方法模式抽象工厂模式单例模式适配器模式组合模式装饰...

《设计模式》实验指导书

哈尔滨理工大学计算机学院实验教学中心设计模式实验实验指导书3实验一Factory模式与AbstractFactory模式3实验二Adapter模式14实验三Observer模式18实验四Interpreter模...

设计模式实验报告(21篇)