zoukankan      html  css  js  c++  java
  • Java版多人聊天室

    server.java

      1 import java.io.*;
      2 import java.net.*;
      3 import java.text.SimpleDateFormat;
      4 import java.util.*;
      5 import java.awt.*;
      6 import javax.swing.*;
      7 
      8 @SuppressWarnings("serial")
      9 public class Server extends JFrame {
     10     // Text area for displaying data
     11     private JTextArea jta = new JTextArea();
     12     ArrayList<Client> clients = new ArrayList<Client>();
     13     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     14     Date d = new Date();
     15     String time = format.format(d);
     16     // Statistics the number of clients
     17     int clientNo = 0;
     18 
     19     public static void main(String[] args) {
     20         new Server();
     21     }
     22 
     23     public Server() {
     24         // Place text area on the frame
     25         setLayout(new BorderLayout());
     26         add(new JScrollPane(jta), BorderLayout.CENTER);
     27 
     28         setTitle("Server");
     29         setSize(500, 300);
     30         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     31         setVisible(true); // It is necessary to show the frame here!
     32 
     33         ServerSocket serverSocket = null;
     34         try {
     35             // Create a server socket
     36             serverSocket = new ServerSocket(2014);
     37         } catch (IOException ex) {
     38             jta.append(" ***端口已被占用!*** " + '
    ');
     39         }
     40         jta.append(" ***服务器启动时间: " + time + "***" + '
    ');
     41 
     42         while (true) {
     43             Socket socket = null;
     44             try {
     45                 // Listen for a connection request
     46                 socket = serverSocket.accept();
     47             } catch (IOException e) {
     48                 e.printStackTrace();
     49             }
     50             // To display client inetAddress
     51             InetAddress inetAddress = socket.getInetAddress();
     52             clientNo++;
     53             jta.append(" Client " + clientNo + '
    ');
     54             jta.append(" Host name is " + inetAddress.getHostName() + '
    ');
     55             jta.append(" IP Address is " + inetAddress.getHostAddress() + '
    ');
     56 
     57             // Create a new Thread for client
     58             Client task = new Client(socket);
     59             clients.add(task);
     60             new Thread(task).start();
     61         }
     62     }
     63 
     64     class Client implements Runnable {
     65         Socket socket;
     66         // Create data input and output streams
     67         DataInputStream inputFromClient = null;
     68         DataOutputStream outputToClient = null;
     69         Client c = null;
     70 
     71         public Client(Socket socket) {
     72             this.socket = socket;
     73             try {
     74                 inputFromClient = new DataInputStream(socket.getInputStream());
     75             } catch (IOException e) {
     76                 e.printStackTrace();
     77             }
     78             try {
     79                 outputToClient = new DataOutputStream(socket.getOutputStream());
     80             } catch (IOException e) {
     81                 e.printStackTrace();
     82             }
     83         }
     84 
     85         public void sentAll(String str) {
     86             try {
     87                 // Receive message from the client
     88                 outputToClient.writeUTF(str);
     89             } catch (SocketException e) {
     90                 if (c != null)
     91                     clients.remove(c);
     92             } catch (IOException e) {
     93                 e.printStackTrace();
     94             }
     95         }
     96 
     97         public void run() {
     98             try {
     99                 while (true) {
    100                     // Receive sentence from the client
    101                     String sentence = inputFromClient.readUTF();
    102                     // Send sentence back to the client
    103                     for (int i = 0; i < clients.size(); i++) {
    104                         c = clients.get(i);
    105                         c.sentAll(sentence);
    106                     }
    107 
    108                     // Display to the text area
    109                     jta.append(" " + time + "
    ");
    110                     jta.append(" " + sentence + '
    ');
    111                 }
    112             } catch (IOException e) {
    113                 // e.printStackTrace();
    114                 clientNo--;
    115                 if (clientNo == 0) {
    116                     jta.append(" ***无客户端连接!***" + "
    ");
    117                     clients.remove(c); // 防止新用户使用
    118                 } else {
    119                     jta.append(" ***退出一用户! 剩余用户: " + clientNo + "***" + "
    ");
    120                 }
    121             }
    122         }
    123     }
    124 }

    client.java

      1 import java.io.*;
      2 import java.net.*;
      3 import java.text.SimpleDateFormat;
      4 import java.util.Date;
      5 import java.awt.*;
      6 import java.awt.event.*;
      7 import javax.swing.*;
      8 
      9 @SuppressWarnings("serial")
     10 public class Client extends JFrame {
     11     // Text field for receiving data
     12     private JTextField jtfName = new JTextField(); // Enter Name
     13     private JTextField jtfMessage = new JTextField(); // Enter Message
     14 
     15     // Text Area to display data
     16     private JTextArea jta = new JTextArea();
     17 
     18     // Button for send massage
     19     private JButton jbSend = new JButton("Send");
     20 
     21     // IO streams
     22     private DataOutputStream toServer;
     23     private DataInputStream fromServer;
     24 
     25     public static void main(String[] args) {
     26         new Client();
     27     }
     28 
     29     public Client() {
     30         // Panel p to hold the label and text field
     31         JPanel p = new JPanel();
     32         p.setLayout(new GridLayout(2, 2));
     33         p.add(new JLabel(" Enter Name: "));
     34         p.add(jtfName);
     35         p.add(new JLabel(" Enter Message: "));
     36         p.add(jtfMessage);
     37         jtfName.setHorizontalAlignment(JTextField.LEFT);
     38         jtfMessage.setHorizontalAlignment(JTextField.LEFT);
     39 
     40         setLayout(new BorderLayout());
     41         add(p, BorderLayout.NORTH);
     42         add(new JScrollPane(jta), BorderLayout.CENTER);
     43         add(jbSend, BorderLayout.SOUTH);
     44 
     45         // Register listener for jbSend button
     46         jbSend.addActionListener(new ButtonListener());
     47 
     48         // Register listener for jtfName JTextField
     49         jtfName.addActionListener(new ButtonListener());
     50 
     51         // Register listener for jtfMessage JTextField
     52         jtfMessage.addActionListener(new ButtonListener());
     53 
     54         setTitle("Client");
     55         setSize(500, 300);
     56         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     57         setVisible(true); // It is necessary to show the frame here!
     58 
     59         try {
     60             // Create a socket to connect to the server
     61             Socket socket = new Socket("localhost", 2014);
     62 
     63             // Create an input stream to receive data from the server
     64             fromServer = new DataInputStream(socket.getInputStream());
     65 
     66             // Create an output stream to send data to the server
     67             toServer = new DataOutputStream(socket.getOutputStream());
     68 
     69             // Receive data from the server all the time
     70             while (true) {
     71                 // read data from client
     72                 String sentence = fromServer.readUTF();
     73                 SimpleDateFormat format = new SimpleDateFormat(
     74                         "yyyy-MM-dd HH:mm:ss");
     75                 Date d = new Date();
     76                 String time = format.format(d);
     77 
     78                 // Display to the text area
     79                 jta.append(" " + time + "
    ");
     80                 jta.append(" " + sentence + "
    ");
     81             }
     82         } catch (IOException ex) {
     83             jta.append(" ***服务器连接失败!***" + '
    ');
     84         }
     85     }
     86 
     87     private class ButtonListener implements ActionListener {
     88         public void actionPerformed(ActionEvent e) {
     89             try {
     90                 // Get the Name and Message from the text field
     91                 String Name = jtfName.getText().trim();
     92                 String Message = jtfMessage.getText().trim();
     93                 // Prevent send a blank message
     94                 if (Name != null && Name.length() != 0 && Message != null
     95                         && Message.length() != 0) {
     96                     String data = Name + ": " + Message;
     97 
     98                     // Send the data to the server
     99                     toServer.writeUTF(data);
    100                     toServer.flush();
    101                 } else
    102                     jta.append(" ***警告:名称和内容均不能为空!*** " + "
    ");
    103 
    104             } catch (IOException ex) {
    105                 System.err.println(ex);
    106             }
    107         }
    108     }
    109 }

    下载链接: http://pan.baidu.com/s/1i3oQlyl 密码: jk6q

    作者:何海洋
    本博客内容主要以学习、研究和分享为主,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    Spark架构分析
    mr运行出错,解决办法
    hbase调优
    虚拟机长时间不关造成的问题
    crontab 使用
    虚拟机克隆网络问题的解决
    ligerui.grid.extend.rowSpan
    64位下安装Scrapy 报错 "could not find openssl.exe" 的解决方法。
    EventBus 事件总线之我的理解
    MongoDB 系列(二) C# 内嵌元素操作 聚合使用
  • 原文地址:https://www.cnblogs.com/hehaiyang/p/3641624.html
Copyright © 2011-2022 走看看