聊天室小程式,

來源:互聯網
上載者:User

聊天室小程式,
聊天室小程式

 思路:

伺服器端:

 1.伺服器端首先得執行個體化一個serversocket來等待用戶端的串連

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 }

結果:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.