Socket和多线程编程的聊天程序实现.docx

上传人:b****5 文档编号:7148662 上传时间:2023-01-21 格式:DOCX 页数:14 大小:40.04KB
下载 相关 举报
Socket和多线程编程的聊天程序实现.docx_第1页
第1页 / 共14页
Socket和多线程编程的聊天程序实现.docx_第2页
第2页 / 共14页
Socket和多线程编程的聊天程序实现.docx_第3页
第3页 / 共14页
Socket和多线程编程的聊天程序实现.docx_第4页
第4页 / 共14页
Socket和多线程编程的聊天程序实现.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

Socket和多线程编程的聊天程序实现.docx

《Socket和多线程编程的聊天程序实现.docx》由会员分享,可在线阅读,更多相关《Socket和多线程编程的聊天程序实现.docx(14页珍藏版)》请在冰豆网上搜索。

Socket和多线程编程的聊天程序实现.docx

Socket和多线程编程的聊天程序实现

一、       课题内容和要求

1.课题内容

基于Socket和多线程编程的聊天程序实现

2.课题要求

网络聊天程序设计非常复杂,允许多个人同时聊天更加需要多线程技术的支持,请实现一个简单的多线程网络聊天程序模拟。

二、       设计思路分析

1.   在网络越来越发达的今天,人们对网络的依赖越来越强,网络聊天已经成了许多人生活中必不可少的一部分,基于这样的需求,出现了许多网络聊天通信工具,像QQ,MSN等等,但是人们已经不再满足于单一的两个人之间的聊天,而是对多人同时聊天产生了兴趣,于是出现了网络聊天室,不同地方的人可以在那个虚拟的聊天室里面热烈聊天。

基于这样的想法,我们用JAVA设计一个多人同时聊天的小程序,用Socket编程实现网络通讯,面向连接的,采用多线程的实现技术。

2.   在程序中,可以设置加入连接的最大数目,通过更改IP地址和端口号,成为不同的客户端,与服务器端连接,进行多用户聊天。

3.   为方便用户交互,我们采用图形化的用户界面。

实现了好友添加,消息收发、显示等基本功能。

三、       概要设计

该网络聊天程序大致分为三个主要部分:

客户端、服务器端和用户图形界面。

各个部分的初步设计思想、流程及存储结构如下:

1.   程序整体框架:

主程序监听一端口,等待客户接入;同时构造一个线程类,准备接管会话。

当一个Socket会话产生后,将这个会话交给线程处理,然后主程序继续监听。

 

打开Socket

命名

监听端口

建立连接

收发消息

关闭连接

打开Socket

 

连接服务器

收发消息

关闭连接

服务器端程序

客户端程序

 

2.   客户端(Client)

客户端,使用Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。

客户端不需要指定打开的端口,通常临时的、动态的分配一个端口。

3.   服务器端(Server)

服务器端,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。

4.   用户图形界面

用户图形界面方便程序与用户的交互,多个用户参加,完成会话功能,具体的设计要方便用户的使用,直观清晰,简洁明了,友好美观。

5.   存储结构

下面列出主要存储结构或变量:

存储结构、变量、对象

类型

说明

post

InetAddress

标识IP地址

Port

int

标识端口

Server[]

ServerThread

服务器端连接数

Client[]

Socket

客户端连接数

Client(Stringip,intp,Facechat)

public

Client类成员函数

Publicvoidrun()

Void

Client、Server类成员函数

Server(intport,Facechat)

public

Server类成员函数

Face()

Public

Face类成员函数

 

四、       详细设计

   代码分服务器端、客户端、和用户图形界面三部分,分别如下:

1.服务器端

服务器端主要是使用ServerSocket类,相当于服务器Socket,用来监听试图进入的连接,当新的连接建立后,该类为他们实例化一个Socket对象,同时得到输入输出流,调用相应方法完成会话。

具体代码如下:

packagenupt.java.socket;

importjava.awt.*;

import.*;

importjava.io.*;

publicclassServerextendsThread{

ServerSocketskt;  //ServerSocket类监听进入的连接,为每个新的连接产生一个Socket对象      

   SocketClient[]=newSocket[10];

   SocketClient1=null;

   inti=0;

   TextAreain;

   intport,k=0,l=0;

   PrintStreamtheOutputStream;

   Facechat;

   publicServer(intport,Facechat){

       try{

           this.port=port;

           skt=newServerSocket(port);

           this.chat=chat;

       }catch(IOExceptione){

           chat.ta.append(e.toString());

       }

   }

   publicvoidrun(){

       chat.ta.append("等待连线......");

       while(true){

           try{

           Client[k]=skt.accept();

                                            //当有客户端连接时就新建一个子线程

           if(i<2){

             ServerThreadserver[]=newServerThread[10];

             server[k]=newServerThread(Client[k],this.chat,i);

                l=server.length;

                server[k].start();

               chat.ta.append(“客户端“+Client[k].getInetAddress()+"已连线\n");

               

               //for(intj=0;j

               theOutputStream=newPrintStream(server[k].getClient().getOutputStream());

               i=server[k].getI();

               k++;

           }else{

               //theOutputStream=newPrintStream(null);

           }

       }catch(SocketExceptione){

           }catch(IOExceptione){

               chat.ta.append(e.toString());

           }

       }

   }

   publicvoiddataout(Stringdata){

       //for(intj=0;j

       theOutputStream.println(data);

   }

}

classServerThreadextendsThread{

   ServerSocketskt;

   SocketClient;

   TextAreain;

   intport,i;

   BufferedReadertheInputStream;

   PrintStreamtheOutputStream;

   Stringreadin;

   Facechat;

//服务端子线程

   publicServerThread(Sockets,Facechat,inti){

       this.i=++i;

       Client=s;

       this.chat=chat;

   }

   publicintgetI(){

       returnthis.i;

   }

   publicSocketgetClient(){

       returnthis.Client;

   }

   publicvoidrun(){

         try{

           theInputStream=newBufferedReader(newInputStreamReader(Client

                   .getInputStream()));

           theOutputStream=newPrintStream(Client.getOutputStream());

           while(true){

               readin=theInputStream.readLine();

               chat.ta.append(readin+"\n");

           }

       }catch(SocketExceptione){

           chat.ta.append("连线中断!

\n");

                          //设置组件可用性

           chat.clientBtn.setEnabled(true);

           chat.serverBtn.setEnabled(true);

           chat.tfaddress.setEnabled(true);

           chat.tfport.setEnabled(true);

           try{

               i--;

               skt.close();

               Client.close();

           }catch(IOExceptionerr){

               chat.ta.append(err.toString());

           }

       }catch(IOExceptione){

           chat.ta.append(e.toString());

       }

   }

   publicvoiddataout(Stringdata){

       theOutputStream.println(data);

   }

}

2.客户端

客户端主要是使用Socket类,该类是JAVA实现网络编程重要的基础类,实现程序间双向的面向连接的通信。

调用publicSocket(Stringhost,intport)方法设定IP和端口。

建好连接后,用户通过得到Socket的输入输出流对象后,利用流的方法实现数据的传输。

调用publicInputStreamgetInputStream()和publicOutputStreamgetOutputStream()方法,分别得到Socket对象的输入输出流;

具体实现代码如下:

packagenupt.java.socket;

import.*;

importjava.io.*;

importjavax.swing.Timer;

publicclassClientextendsThread{

     Socketskt;                                 //用于客户端的连接

   InetAddresshost;                       //主机地址

   intport;                                    //端口号

   BufferedReadertheInputStream;

   PrintStreamtheOutputStream;

   Stringreadin;

   Facechat;

   publicClient(Stringip,intp,Facechat){

       try{

           host=InetAddress.getByName(ip);           //获取IP地址

           port=p;                                                 //获取端口号

           this.chat=chat;

       }catch(IOExceptione){

           chat.ta.append(e.toString());

       }

   }

   publicvoidrun(){

       try{

           chat.ta.append("准备连线,稍后!

");

           skt=newSocket(host,port);                    //新建Socket对象

           chat.ta.append("成功\n");                  //缓冲区末尾添加字符串

           theInputStream=newBufferedReader(newInputStreamReader(skt.getInputStream()));

           theOutputStream=newPrintStream(skt.getOutputStream());

           while(true){

               readin=theInputStream.readLine();

               chat.ta.append(readin+"\n");

           }

       }catch(SocketExceptione){

           chat.ta.append("未连上!

\n");

           chat.clientBtn.setEnabled(true);

           chat.serverBtn.setEnabled(true);

           chat.tfaddress.setEnabled(true);

           chat.tfport.setEnabled(true);

           try{

               skt.close();

           }catch(IOExceptionerr){

               chat.ta.append(err.toString());

           }

       }catch(IOExceptione){

           chat.ta.append(e.toString());

       }

   }

   publicvoiddataout(Stringdata){

       theOutputStream.println(data);

   }

}

3.用户图形界面

该部分主要是完成界面的初始化,合理布局组件,方便用户交互。

主要是JAVA按钮,文本域,标签,布局管理器的使用。

主要处理了键盘Enter消息接受,下面是实现代码:

packagenupt.java.socket;

importjava.awt.*;

importjava.awt.event.*;

publicclassFaceextendsFrame{

     

     privatestaticfinallongserialVersionUID=1L;

   ButtonclientBtn,serverBtn;

   TextAreata;

   TextFieldtfaddress,tfport,tftype;

   Labellbl1,lbl2,lbl3;

   intport;

   Clientclient;

   Serverserver;

   booleaniamserver;

   staticFacefrm;

   publicFace(){

        //实例化组件

       clientBtn=newButton("客户端");

       serverBtn=newButton("服务器");

       ta=newTextArea("",10,50,TextArea.SCROLLBARS_BOTH);

       lbl1=newLabel("IP地址:

");

       tfaddress=newTextField("192.168.1.104",10);

       lbl2=newLabel("端口:

");

       tfport=newTextField("8080");

       lbl3=newLabel("发送内容:

");

       tftype=newTextField(40);

       tftype.addKeyListener(newTFListener());

       ta.setEditable(false);

       //向容器中加入以上组件

       setLayout(new  FlowLayout());

       add(lbl1);

       add(tfaddress);

       add(lbl2);

       add(tfport);

       add(clientBtn);

       add(serverBtn);

       add(ta);

       add(lbl3);

       add(tftype);

       //设置格式

       setLocation(400,250);               //窗口显示再屏幕的位置坐标

       setSize(400,300);                     //设置窗体大小

       setTitle("基于Socket和多线程编程的聊天程序");

       this.setVisible(true);                  //设置窗体可见

       //事件响应

       clientBtn.addActionListener(newActionListener(){

           publicvoidactionPerformed(ActionEvente){

               port=Integer.parseInt(tfport.getText());

               client=newClient(tfaddress.getText(),port,frm);

               client.start();

               tfaddress.setEnabled(false);

               tfport.setEnabled(false);

               serverBtn.setEnabled(false);

               clientBtn.setEnabled(false);

           }

       });

       serverBtn.addActionListener(newActionListener(){

           publicvoidactionPerformed(ActionEvente){

               port=Integer.parseInt(tfport.getText());

               server=newServer(port,frm);

               server.start();

               iamserver=true;

               tfaddress.setText("成为服务器");

               tfaddress.setEnabled(false);

               tfport.setEnabled(false);

               serverBtn.setEnabled(false);

               clientBtn.setEnabled(false);

           }

       });

       addWindowListener(newWindowAdapter(){

           publicvoidwindowClosing(WindowEvente){

               System.exit(0);

           }

       });

   }

     publicstaticvoidmain(String[]args){       //主方法

            //TODOAuto-generatedmethodstub

            

            frm=newFace();

     }

     privateclassTFListeneri

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高中教育 > 初中教育

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1