Socket和多线程编程的聊天程序实现_第1页
Socket和多线程编程的聊天程序实现_第2页
Socket和多线程编程的聊天程序实现_第3页
Socket和多线程编程的聊天程序实现_第4页
Socket和多线程编程的聊天程序实现_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、精选优质文档-倾情为你奉上一、        课题内容和要求1.课题内容基于Socket和多线程编程的聊天程序实现2.课题要求网络聊天程序设计非常复杂,允许多个人同时聊天更加需要多线程技术的支持,请实现一个简单的多线程网络聊天程序模拟。二、        设计思路分析1.    在网络越来越发达的今天,人们对网络的依赖越来越强,网络聊天已经成了许多人生活中必不可少的一部分,基于这样的需求,出现了许多网络聊天通信工具,像QQ,M

2、SN等等,但是人们已经不再满足于单一的两个人之间的聊天,而是对多人同时聊天产生了兴趣,于是出现了网络聊天室,不同地方的人可以在那个虚拟的聊天室里面热烈聊天。基于这样的想法,我们用JAVA设计一个多人同时聊天的小程序,用Socket编程实现网络通讯,面向连接的,采用多线程的实现技术。2.    在程序中,可以设置加入连接的最大数目,通过更改IP地址和端口号,成为不同的客户端,与服务器端连接,进行多用户聊天。3.    为方便用户交互,我们采用图形化的用户界面。实现了好友添加,消息收发、显示等基本功能。三、  

3、0;     概要设计该网络聊天程序大致分为三个主要部分:客户端、服务器端和用户图形界面。各个部分的初步设计思想、流程及存储结构如下:1.    程序整体框架:主程序监听一端口,等待客户接入;同时构造一个线程类,准备接管会话。当一个Socket会话产生后,将这个会话交给线程处理,然后主程序继续监听。 打开Socket命 名监听端口建立连接收发消息关闭连接打开Socket 连接服务器收发消息关闭连接服务器端程序客户端程序 2.    客户端(Client)客户端,使用

4、Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个端口。3.    服务器端(Server)服务器端,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。4.    用户图形界面用户图形界面方便程序与用户的交互,多个用户参加,完成会话功能,具体

5、的设计要方便用户的使用,直观清晰,简洁明了,友好美观。5.    存储结构下面列出主要存储结构或变量:存储结构、变量、对象类型说明postInetAddress标识IP地址Portint标识端口Server ServerThread服务器端连接数Client Socket客户端连接数Client(String ip,int p,Face chat)publicClient类成员函数Public void run()VoidClient、Server类成员函数Server(int port,Face chat)publicServer类成员函数Face()Publi

6、cFace类成员函数 四、        详细设计    代码分服务器端、客户端、和用户图形界面三部分,分别如下:1.服务器端服务器端主要是使用ServerSocket类,相当于服务器Socket,用来监听试图进入的连接,当新的连接建立后,该类为他们实例化一个Socket对象,同时得到输入输出流,调用相应方法完成会话。具体代码如下:package nupt.java.socket;import java.awt.*;import .*;import java.io.*;public c

7、lass Server extends Thread ServerSocket skt;   / ServerSocket类监听进入的连接,为每个新的连接产生一个Socket对象          Socket Client =new Socket10;    Socket Client1=null;    int i = 0;    TextArea in;   

8、int port,k=0,l=0;    PrintStream theOutputStream;    Face chat;    public Server(int port, Face chat)         try             this.port = port;   

9、0;        skt = new ServerSocket(port);            this.chat = chat;        catch (IOException e)             chat.ta.ap

10、pend(e.toString();                public void run()         chat.ta.append("等待连线.");        while (true)         &#

11、160;   try             Clientk = skt.accept();                                &#

12、160;             /当有客户端连接时就新建一个子线程            if (i < 2)               ServerThread server = new ServerThread10; 

13、;             serverk= new ServerThread(Clientk, this.chat, i);                 l=server.length;          

14、0;      serverk.start();                chat.ta.append(“客户端“+ Clientk.getInetAddress() + "已连线n");               

15、60;               /for(int j=0;j<server.length;j+)                theOutputStream = new PrintStream(serverk.getClient().getOutputStream();  &#

16、160;             i = serverk.getI();                k+;             else       &

17、#160;         /theOutputStream = new PrintStream(null);                    catch (SocketException e)             ca

18、tch (IOException e)                 chat.ta.append(e.toString();                            public void d

19、ataout(String data)         /for(int j=0;j<l;j+)        theOutputStream.println(data);    class ServerThread extends Thread     ServerSocket skt;    Socket Client;   

20、TextArea in;    int port,i;    BufferedReader theInputStream;    PrintStream theOutputStream;    String readin;    Face chat;/服务端子线程    public ServerThread(Socket s, Face chat, int i)     &#

21、160;   this.i = +i;        Client = s;        this.chat = chat;        public int getI()         return this.i;        public

22、 Socket getClient()         return this.Client;        public void run()           try             theInputStream = new BufferedReader(

23、new InputStreamReader(Client                    .getInputStream();            theOutputStream = new PrintStream(Client.getOutputStream();  &

24、#160;         while (true)                 readin = theInputStream.readLine();                chat.ta.append(r

25、eadin + "n");                    catch (SocketException e)             chat.ta.append("连线中断!n");      

26、60;                    / 设置组件可用性            chat.clientBtn.setEnabled(true);            chat.se

27、rverBtn.setEnabled(true);            chat.tfaddress.setEnabled(true);            chat.tfport.setEnabled(true);            try  

28、60;              i - -;                skt.close();                Client.close();

29、60;           catch (IOException err)                 chat.ta.append(err.toString();                

30、    catch (IOException e)             chat.ta.append(e.toString();                public void dataout(String data)         theOutp

31、utStream.println(data);    2.客户端客户端主要是使用Socket类,该类是JAVA实现网络编程重要的基础类,实现程序间双向的面向连接的通信。调用public Socket(String host,int port)方法设定IP和端口。建好连接后,用户通过得到Socket的输入输出流对象后,利用流的方法实现数据的传输。调用public InputStream getInputStream()和public OutputStream getOutputStream()方法,分别得到Socket对象的输入输出流;具体实现代码如下:packag

32、e nupt.java.socket;import .*;import java.io.*;import javax.swing.Timer;public class Client extends Thread       Socket skt;                         &#

33、160;        / 用于客户端的连接    InetAddress host;                        / 主机地址    int port;     

34、0;                               / 端口号    BufferedReader theInputStream;    PrintStream theOutputStream;  

35、0; String readin;    Face chat;    public Client(String ip, int p, Face chat)         try             host = InetAddress.getByName(ip);       

36、60;    / 获取IP地址            port = p;                                &#

37、160;                 / 获取端口号            this.chat = chat;        catch (IOException e)        &

38、#160;    chat.ta.append(e.toString();                public void run()         try             chat.ta.append("准备连线,稍后!"

39、);            skt = new Socket(host, port);                     / 新建Socket对象            ch

40、at.ta.append("成功n");                   / 缓冲区末尾添加字符串            theInputStream = new BufferedReader(new InputStreamReader(skt.getInputStream();

41、60;           theOutputStream = new PrintStream(skt.getOutputStream();            while (true)                 readin =

42、theInputStream.readLine();                chat.ta.append(readin + "n");                    catch (SocketException e)  &#

43、160;          chat.ta.append("未连上!n");            chat.clientBtn.setEnabled(true);            chat.serverBtn.setEnabled(true); 

44、60;          chat.tfaddress.setEnabled(true);            chat.tfport.setEnabled(true);            try        &

45、#160;        skt.close();            catch (IOException err)                 chat.ta.append(err.toString();    

46、0;               catch (IOException e)             chat.ta.append(e.toString();                public void dataout(

47、String data)         theOutputStream.println(data);    3.用户图形界面该部分主要是完成界面的初始化,合理布局组件,方便用户交互。主要是JAVA按钮,文本域,标签,布局管理器的使用。主要处理了键盘Enter消息接受,下面是实现代码:package nupt.java.socket;import java.awt.*;import java.awt.event.*;public class Face extends Frame  &#

48、160;         private static final long serialVersionUID = 1L;    Button clientBtn, serverBtn;    TextArea ta;    TextField tfaddress, tfport, tftype;    Label lbl1,lbl2,lbl3;    int por

49、t;    Client client;    Server server;    boolean iamserver;    static Face frm;    public Face()           / 实例化组件        clientBtn = new Button(&quo

50、t;客户端");        serverBtn = new Button("服务器");        ta = new TextArea("", 10, 50, TextArea.SCROLLBARS_BOTH);        lbl1 = new Label("IP地址:");  

51、0;     tfaddress = new TextField("192.168.1.104", 10);        lbl2 = new Label("端口:");        tfport = new TextField("8080");        lbl3 = new L

52、abel("发送内容:");        tftype = new TextField(40);        tftype.addKeyListener(new TFListener();        ta.setEditable(false);        /向容器中加入以上组件 

53、;       setLayout(new   FlowLayout();        add(lbl1);        add(tfaddress);        add(lbl2);        add(tfport);

54、0;       add(clientBtn);        add(serverBtn);        add(ta);        add(lbl3);        add(tftype);     

55、;   /设置格式        setLocation(400, 250);                /窗口显示再屏幕的位置坐标        setSize(400, 300);        

56、60;             /设置窗体大小        setTitle("基于Socket和多线程编程的聊天程序");        this.setVisible(true);           &

57、#160;       /设置窗体可见        /事件响应        clientBtn.addActionListener(new ActionListener()             public void actionPerformed(ActionEvent e) &

58、#160;               port = Integer.parseInt(tfport.getText();                client = new Client(tfaddress.getText(), port, frm);    &#

59、160;           client.start();                tfaddress.setEnabled(false);                tfport.set

60、Enabled(false);                serverBtn.setEnabled(false);                clientBtn.setEnabled(false);        

61、;            );        serverBtn.addActionListener(new ActionListener()             public void actionPerformed(ActionEvent e)      

62、60;          port = Integer.parseInt(tfport.getText();                server = new Server(port, frm);             &

63、#160;  server.start();                iamserver = true;                tfaddress.setText("成为服务器");      &

64、#160;         tfaddress.setEnabled(false);                tfport.setEnabled(false);                serverBtn.s

65、etEnabled(false);                clientBtn.setEnabled(false);                    );        addWindow

66、Listener(new WindowAdapter()             public void windowClosing(WindowEvent e)                 System.exit(0);         

67、60;          );          public static void main(String args)         /主方法             / TODO Auto-generated method stub 

68、;                        frm = new Face();            private class TFListener implements KeyListener      

69、60;  public void keyPressed(KeyEvent e)           if (e.getKeyCode() = KeyEvent.VK_ENTER) /按Enter输出显示聊天内容                ta.append(">" + tftype.getText() + "n");               

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论