聊天室小程序

匿名 (未验证) 提交于 2019-12-02 21:53:32

聊天室小程序

服务器端:

2.用户端连接后获取套接字的输入输出流,读取客户端发送过来的数据,然后发送到每一个连接到该服务器的客户端上

客户端:

1.实例化socket连接上对应的服务器

2.有信息发送时将数据写入,然后接受服务器端发送过来的数据

3.断开连接时,关闭数据输入输出流,关闭套接字

服务器端代码:

  1 public class Server extends JFrame {   2     /**   3      *    4      */   5     private static final long serialVersionUID = 1L;   6     private ServerSocket ss = null;   7     private boolean bStart = false;   8        9     private JTextArea taContent = new JTextArea();  10       11     private int index = 0; //连接的客户端数量  12       13     List<Client> clients = new ArrayList<Client>(); //存放客户端对象  14       15     public void launchFrame() {  //处理Frame  16         taContent.setEditable(false);  //设置文本域不可编辑  17           18         taContent.setBackground(Color.DARK_GRAY);  19         taContent.setForeground(Color.YELLOW);  20         this.add(taContent);  21         this.setSize(300, 350);  22         this.setLocation(400, 200);  23         this.setTitle("TCP Server");  24         this.setVisible(true);  25         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  26         tcpMonitor();  27     }  28       29     public void tcpMonitor() {  30         try {  31             ss = new ServerSocket(8888); //实例化serversocket等待客户端连接  32             bStart = true;  33         } catch (IOException e) {  34               35             e.printStackTrace();  36         }  37           38         try {  39             while (bStart) {  40                 index++;  41                 Socket s = ss.accept();  42                 Client c = new Client(s);  //实例化对象同时获取套接字的输入输出流  43                 clients.add(c);  44                   45                 taContent.append(s.getInetAddress().getHostAddress()  46                         + " connected " + index + " clients\n");  47                 new Thread(c).start();  48                   49             }  50         } catch (IOException e) {  51             e.printStackTrace();  52         } finally {  53             try {  54                 ss.close();  55             } catch (IOException e) {  56                   57                 e.printStackTrace();  58             }  59         }  60           61     }  62       63     public static void main(String args[]) {  64         Server ts = new Server();  65         ts.launchFrame();  66     }  67       68     private class Client implements Runnable {  69         DataInputStream dis = null;  70         DataOutputStream dos = null;  71           72         Socket s = null;  73         boolean bStart = false;  74           75         Client(Socket s) {  76             this.s = s;  77             try {  78                 dis = new DataInputStream(s.getInputStream());  79                 dos = new DataOutputStream(s.getOutputStream());  80             } catch (IOException e) {  81                 e.printStackTrace();  82             }  83               84             bStart = true;  85         }  86           87         public void sendToEveryClient(String str) {  88             try {  89                 dos.writeUTF(str);  90                 dos.flush();  91                   92             } catch (IOException e) {  93                 index--;  94                 clients.remove(this);  95                 taContent.append(s.getInetAddress().getHostAddress()  96                         + " exited " + index + " clients\n");  97                 System.out.println("对方退出了!我从List里面去掉了!");  98             }  99         } 100          101         public void run() { 102             try { 103                 while (bStart) { 104                     String str = dis.readUTF(); 105                     System.out.println(str); 106                     for (int i = 0; i < clients.size(); i++) { 107                         Client c = clients.get(i); 108                         c.sendToEveryClient(str); 109                     } 110                 } 111             } catch (EOFException e) { 112                 clients.remove(this); 113                 taContent.append(s.getInetAddress().getHostAddress() 114                         + " exited " + clients.size() + " clients\n"); 115                 System.out.println("client closed"); 116             } catch (SocketException e) { 117                 System.out.println("client closed"); 118             } catch (IOException e) { 119                 e.printStackTrace(); 120             } finally { 121                 try { 122                     if (s != null) 123                         s.close(); 124                     if (dis != null) 125                         dis.close(); 126                     if (dos != null) 127                         dos.close(); 128                 } catch (IOException e) { 129                     e.printStackTrace(); 130                 } 131             } 132         } 133          134     } 135      136 }

客户端代码:

  1 public class Client extends JFrame {   2     /**   3      *    4      */   5     private static final long serialVersionUID = 1L;   6     TextArea taContent = new TextArea();   7     JTextField tfTxt = new JTextField(20);   8        9     JButton send = new JButton("发送");  10     JButton connect = new JButton("连接");  11     JButton clear = new JButton("清空");  12       13     boolean live = false;  14     JPanel p1 = new JPanel();  15     JPanel p2 = new JPanel();  16       17     Socket s = null;  18     DataOutputStream dos = null;  19     DataInputStream dis = null;  20       21     boolean bConnected = false;  22       23     Thread t = new Thread(new RecToServer()); //从服务器端接收数据  24       25     public void launchFrame() {  26           27         taContent.setEditable(false);  28           29         p2.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));  30         p2.add(send);  31         p2.add(connect);  32         p2.add(clear);  33           34         Container con = this.getContentPane();  35           36         con.add(taContent, "North");  37         con.add(tfTxt, "Center");  38         con.add(p2, "South");  39           40         this.setSize(300, 350);  41         this.setLocation(400, 200);  42         this.setTitle("Chat Client");  43           44         this.setVisible(true);  45         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  46           47         connect.addActionListener(new Connect());  48         send.addActionListener(new SendMsg());  49         clear.addActionListener(new ActionListener() {  50             public void actionPerformed(ActionEvent e) {  51                 taContent.setText("");  52             }  53         });  54     }  55       56     public void connectToServer() {  57         try {  58               59             s = new Socket("127.0.0.1", 8888);  60             dos = new DataOutputStream(s.getOutputStream());  61             dis = new DataInputStream(s.getInputStream());  62               63             bConnected = true;  64               65         } catch (BindException e) {  66             System.out.println("找不到指定的服务器");  67         } catch (UnknownHostException e) {  68             // TODO Auto-generated catch block  69             e.printStackTrace();  70         } catch (IOException e) {  71             // TODO Auto-generated catch block  72             e.printStackTrace();  73         }  74           75     }  76       77     public void disConnect() {  78         try {  79             if (s != null) {  80                 s.close();  81             }  82               83             if (dos != null) {  84                 dos.close();  85             }  86             if (dis != null) {  87                 dis.close();  88             }  89         } catch (IOException e) {  90             e.printStackTrace();  91         }  92     }  93       94     public static void main(String args[]) {  95         Client tc = new Client();  96         tc.launchFrame();  97     }  98       99     private class Connect implements ActionListener { 100         public void actionPerformed(ActionEvent e) { 101             if (e.getActionCommand() == "连接") { 102                  103                 connectToServer(); 104                 try { 105                     t.start(); 106                 } catch (IllegalThreadStateException ex) { 107                      108                 } 109                  110                 connect.setText("断开连接"); 111                  112             } else if (e.getActionCommand() == "断开连接") { 113                 disConnect(); 114                 connect.setText("连接"); 115             } 116              117         } 118     } 119      120     private class SendMsg implements ActionListener { 121         public void actionPerformed(ActionEvent e) { 122             if (connect.getActionCommand() == "连接") { 123                 JOptionPane.showMessageDialog(Client.this, 124                         "没有找到指定的服务器", "错误提示", 1); 125             } else { 126                 String str = tfTxt.getText(); 127                 tfTxt.setText(""); 128                  129                 try { 130                     dos.writeUTF(str); 131                     dos.flush(); 132                 } catch (SocketException ex) { 133                     System.out.println("没有找到指定的服务器"); 134                     JOptionPane.showMessageDialog(Client.this, 135                             "没有找到指定的服务器", "错误提示", 1); 136                 } catch (IOException ex) { 137                     ex.printStackTrace(); 138                 } 139             } 140              141         } 142     } 143      144     private class RecToServer implements Runnable { 145         public void run() { 146             try { 147                 while (bConnected) { 148                     String str = dis.readUTF(); 149                     // System.out.println(str); 150                      151                     taContent.append(str + "\n"); 152                 } 153             } catch (SocketException e) { 154                 System.out.println("服务器已关闭"); 155             } catch (IOException e) { 156                 e.printStackTrace(); 157             } 158         } 159     } 160 }

结果:

文章来源: 聊天室小程序
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!