(Java) 聊天室
- Server(伺服器端) :
-
-
-
-
-
-
- package chats_.multi;
-
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.SocketException;
- import java.util.ArrayList;
- import java.util.LinkedList;
- import java.util.*;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.DefaultListModel;
- import javax.swing.JOptionPane;
-
-
-
-
-
- public class Server extends javax.swing.JFrame {
- LinkedList clientOutputStreams;
- LinkedList<String> users;
- public Server() {
- initComponents();
- }
- public class ClinetHandler implements Runnable{
- Socket socket ;
- PrintWriter out ;
- BufferedReader in ;
- public ClinetHandler(Socket s , PrintWriter o){
- try {
- socket = s ;
- out = o ;
- in = new BufferedReader(new InputStreamReader(s.getInputStream()));
- } catch (IOException ex) {
- System.out.println("ERROR");
- }
- }
- @Override
- public void run() {
- String mess ;
- String conn = "連接";
- String exit = "離開";
- String chat = "聊天";
- String[] data;
- String username = "";
- try{
- while((mess = in.readLine()) != null){
- jTextArea1.append(" 收到 : "+ mess + " \n");
- data = mess.split(":");
- username = data[0];
- if(data[2].equals(conn)){
- telleveryone(data[0]+":"+data[1]+":"+chat);
- telleveryone("::重置");
- addUeser(data[0]);
- }else if(data[2].equals(exit)){
- telleveryone(data[0]+":"+data[1]+":"+chat);
- telleveryone("::重置");
- removeUeser(data[0]);
- }else if(data[2].equals(chat)){
- telleveryone(mess);
- }else{
- jTextArea1.append(" 沒有滿足條件 \n");
- }
- }
-
- }catch(Exception e){
- try {
- socket.close();
- jTextArea1.append(" 失去一個使用者連線 \n");
-
- clientOutputStreams.remove(out);
- telleveryone("::重置");
- removeUeser(username);
- } catch (IOException ex) {
- ex.printStackTrace();
- JOptionPane.showMessageDialog(null, "關閉錯誤....");
- System.exit(-1);
- }
- }
- }
-
-
-
- }
-
- private void show_Online_users(){
- DefaultListModel n = new DefaultListModel();
- for(String user : users)
- n.addElement(user);
- Users1.setModel(n);
- }
- private void telleveryone(String mess) {
- Iterator users = clientOutputStreams.iterator() ;
- while(users.hasNext()){
- PrintWriter writer = (PrintWriter) users.next() ;
-
- writer.println(mess);
- writer.flush();
- }
- }
-
- private void addUeser(String username) {
- users.add(username);
- jTextArea1.append(" 使用者 : "+ username + " 加入聊天室\n");
- show_Online_users();
- for(String u : users)
- telleveryone(u+": :連接");
- }
-
- private void removeUeser(String username) {
- users.remove(username);
- show_Online_users();
- jTextArea1.append(" 使用者 : "+ username + " 已經退出聊天室\n");
- for(String u : users)
- telleveryone(u+": :連接");
- }
- public class ServerStart implements Runnable {
-
- @Override
- public void run() {
- clientOutputStreams = new LinkedList();
- users = new LinkedList();
- try{
- ServerSocket ss = new ServerSocket(7788);
- while(true){
- Socket s = ss.accept() ;
- PrintWriter p = new PrintWriter(s.getOutputStream(),true);
- clientOutputStreams.add(p) ;
- new Thread(new ClinetHandler(s , p )).start();
- jTextArea1.append(" 連接到一個使用者\n");
- }
- }catch(Exception e){
- e.printStackTrace();
- JOptionPane.showMessageDialog(null, "連結錯誤", "訊息" , JOptionPane.ERROR_MESSAGE);
- }
- }
-
- }
- @SuppressWarnings("unchecked")
-
- private void initComponents() {
-
- jSeparator1 = new javax.swing.JSeparator();
- jScrollPane1 = new javax.swing.JScrollPane();
- jTextArea1 = new javax.swing.JTextArea();
- jPanel1 = new javax.swing.JPanel();
- ONLINE_USERS = new javax.swing.JButton();
- CLEAR = new javax.swing.JButton();
- BUILLD = new javax.swing.JButton();
- ENDBUT = new javax.swing.JButton();
- jScrollPane2 = new javax.swing.JScrollPane();
- Users1 = new javax.swing.JList<>();
- jLabel1 = new javax.swing.JLabel();
-
- setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
- setTitle("伺服器控制台");
- setMaximumSize(new java.awt.Dimension(465, 575));
- setMinimumSize(new java.awt.Dimension(465, 575));
- setPreferredSize(new java.awt.Dimension(465, 575));
- setResizable(false);
- getContentPane().setLayout(null);
-
- jTextArea1.setBackground(new java.awt.Color(153, 153, 153));
- jTextArea1.setColumns(20);
- jTextArea1.setFont(new java.awt.Font("MS PGothic", 1, 14));
- jTextArea1.setRows(5);
- jTextArea1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4));
- jScrollPane1.setViewportView(jTextArea1);
-
- getContentPane().add(jScrollPane1);
- jScrollPane1.setBounds(10, 10, 343, 405);
-
- jPanel1.setBackground(new java.awt.Color(102, 102, 102));
- jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));
- jPanel1.setLayout(new java.awt.GridLayout(2, 2));
-
- ONLINE_USERS.setBackground(new java.awt.Color(255, 255, 255));
- ONLINE_USERS.setFont(new java.awt.Font("微軟正黑體", 1, 14));
- ONLINE_USERS.setText("使用者剔除");
- ONLINE_USERS.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
- ONLINE_USERS.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- ONLINE_USERSActionPerformed(evt);
- }
- });
- jPanel1.add(ONLINE_USERS);
-
- CLEAR.setBackground(new java.awt.Color(255, 255, 255));
- CLEAR.setFont(new java.awt.Font("微軟正黑體", 1, 14));
- CLEAR.setText("刪除訊息");
- CLEAR.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
- CLEAR.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- CLEARActionPerformed(evt);
- }
- });
- jPanel1.add(CLEAR);
-
- BUILLD.setBackground(new java.awt.Color(255, 255, 255));
- BUILLD.setFont(new java.awt.Font("微軟正黑體", 1, 14));
- BUILLD.setText("建立");
- BUILLD.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
- BUILLD.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- BUILLDActionPerformed(evt);
- }
- });
- jPanel1.add(BUILLD);
-
- ENDBUT.setBackground(new java.awt.Color(255, 255, 255));
- ENDBUT.setFont(new java.awt.Font("微軟正黑體", 1, 14));
- ENDBUT.setText("中止");
- ENDBUT.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
- ENDBUT.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- ENDBUTActionPerformed(evt);
- }
- });
- jPanel1.add(ENDBUT);
-
- getContentPane().add(jPanel1);
- jPanel1.setBounds(10, 430, 340, 100);
-
- Users1.setBackground(new java.awt.Color(153, 153, 153));
- Users1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 3));
- Users1.setFont(new java.awt.Font("微軟正黑體", 1, 18));
- jScrollPane2.setViewportView(Users1);
-
- getContentPane().add(jScrollPane2);
- jScrollPane2.setBounds(360, 10, 90, 410);
-
- jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/chats_/multi/phone-icon.png")));
- jLabel1.setText("jLabel1");
- getContentPane().add(jLabel1);
- jLabel1.setBounds(370, 440, 80, 90);
-
- pack();
- }
-
- private void BUILLDActionPerformed(java.awt.event.ActionEvent evt) {
- Thread start = new Thread(new ServerStart());
- start.start();
- jTextArea1.append(" 建立成功.....");
- }
-
- private void CLEARActionPerformed(java.awt.event.ActionEvent evt) {
- jTextArea1.setText("");
- }
-
- private void ENDBUTActionPerformed(java.awt.event.ActionEvent evt) {
- try {
- Thread.sleep(10000);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- }
- jTextArea1.append("伺服器中斷回應......");
- telleveryone("伺服器已中斷回應......");
- jTextArea1.setText(" ");
- }
-
- private void ONLINE_USERSActionPerformed(java.awt.event.ActionEvent evt) {
- System.out.print(Users1.getSelectedValue());
- telleveryone(Users1.getSelectedValue()+"::離開");
- }
-
-
- public static void main(String args[]) {
-
-
-
-
-
- try {
- for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
- if ("Nimbus".equals(info.getName())) {
- javax.swing.UIManager.setLookAndFeel(info.getClassName());
- break;
- }
- }
- } catch (ClassNotFoundException ex) {
- java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (InstantiationException ex) {
- java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (javax.swing.UnsupportedLookAndFeelException ex) {
- java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- }
-
-
-
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new Server().setVisible(true);
- }
- });
- }
-
-
- private javax.swing.JButton BUILLD;
- private javax.swing.JButton CLEAR;
- private javax.swing.JButton ENDBUT;
- private javax.swing.JButton ONLINE_USERS;
- private javax.swing.JList<String> Users1;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JPanel jPanel1;
- private javax.swing.JScrollPane jScrollPane1;
- private javax.swing.JScrollPane jScrollPane2;
- private javax.swing.JSeparator jSeparator1;
- private javax.swing.JTextArea jTextArea1;
-
- }
-
- clinet(使用者端) :
-
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.*;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.swing.ImageIcon;
- import javax.swing.JOptionPane;
-
-
-
-
-
-
-
-
-
-
-
- public class Clinet extends javax.swing.JFrame {
- String IP ;
- LinkedList<String> users = new LinkedList();
- int port = 7788;
- Boolean isConnected = false;
- Socket socket;
- BufferedReader in;
- PrintWriter out;
- String username;
- public Clinet() {
- initComponents();
- }
- public void IncomingReader(){
- new Thread(new IncomingReader()).start();
- }
- public class IncomingReader implements Runnable{
- String[] data;
- String conn = "連接";
- String exit = "離開";
- String chat = "聊天";
- String reset = "重置";
- String mess , closeData = "";
- @Override
- public void run() {
- try {
- while ((mess = in.readLine()) != null) {
- data = mess.split(":");
- if(data[2].equals(conn)){
- users.add(data[0]);
- }else if(data[2].equals(exit)&&data[0].equals(username)){
- sendExit();
- Disconnect();
- }else if(data[2].equals(chat)){
- jTextArea1.append(data[0]+":"+ data[1] +"\n");
- }else if(data[2].equals(reset)){
- users = new LinkedList();
- }else{
- jTextArea1.append("沒有滿足條件 \n");
- }
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- JOptionPane.showMessageDialog(null , "伺服器關閉...." , "訊息" , JOptionPane.WARNING_MESSAGE);
- }
- }
- }
- @SuppressWarnings("unchecked")
-
- private void initComponents() {
-
- jTextField1 = new javax.swing.JTextField();
- jScrollPane1 = new javax.swing.JScrollPane();
- jTextArea1 = new javax.swing.JTextArea();
- jButton1 = new javax.swing.JButton();
- jButton2 = new javax.swing.JButton();
- jLabel2 = new javax.swing.JLabel();
- jButton3 = new javax.swing.JButton();
- jTextField2 = new javax.swing.JTextField();
- jButton4 = new javax.swing.JButton();
- jButton5 = new javax.swing.JButton();
- jLabel1 = new javax.swing.JLabel();
-
- setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
- setTitle("使用者");
- setMaximumSize(new java.awt.Dimension(458, 580));
- setMinimumSize(new java.awt.Dimension(458, 580));
- setPreferredSize(new java.awt.Dimension(458, 580));
- setResizable(false);
- getContentPane().setLayout(null);
-
- jTextField1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jTextField1ActionPerformed(evt);
- }
- });
- getContentPane().add(jTextField1);
- jTextField1.setBounds(30, 60, 120, 30);
-
- jTextArea1.setColumns(20);
- jTextArea1.setRows(5);
- jScrollPane1.setViewportView(jTextArea1);
-
- getContentPane().add(jScrollPane1);
- jScrollPane1.setBounds(10, 120, 440, 378);
-
- jButton1.setText("登入");
- jButton1.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton1ActionPerformed(evt);
- }
- });
- getContentPane().add(jButton1);
- jButton1.setBounds(180, 70, 130, 23);
-
- jButton2.setText("匿名登入");
- jButton2.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton2ActionPerformed(evt);
- }
- });
- getContentPane().add(jButton2);
- jButton2.setBounds(180, 30, 130, 23);
-
- jLabel2.setFont(new java.awt.Font("微軟正黑體", 1, 14));
- jLabel2.setText("Name :");
- getContentPane().add(jLabel2);
- jLabel2.setBounds(60, 30, 60, 20);
-
- jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/phone-icon (1).png")));
- jButton3.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton3ActionPerformed(evt);
- }
- });
- getContentPane().add(jButton3);
- jButton3.setBounds(370, 500, 60, 50);
- getContentPane().add(jTextField2);
- jTextField2.setBounds(10, 511, 340, 30);
-
- jButton4.setText("離線");
- jButton4.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton4ActionPerformed(evt);
- }
- });
- getContentPane().add(jButton4);
- jButton4.setBounds(320, 70, 120, 23);
-
- jButton5.setText("所有成員");
- jButton5.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- jButton5ActionPerformed(evt);
- }
- });
- getContentPane().add(jButton5);
- jButton5.setBounds(320, 30, 120, 23);
-
- jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "使用者", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("微軟正黑體", 1, 14)));
- getContentPane().add(jLabel1);
- jLabel1.setBounds(10, 0, 440, 110);
-
- pack();
- }
-
- private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
-
- }
-
- private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- if(!isConnected){
- try {
- username = jTextField1.getText();
- jTextField1.setEditable(false);
- socket = new Socket( IP , port );
- out = new PrintWriter(socket.getOutputStream(),true);
- in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- out.println(username + ":"+"已加入聊天"+ ":連接");
- isConnected = true ;
- } catch (IOException ex) {
- JOptionPane.showMessageDialog(null , "沒連接到伺服器 再試一次.... \n");
- jTextField1.setEditable(false);
- }
- IncomingReader();
- }else{
- JOptionPane.showMessageDialog(null , "你已經登入了 \n");
- }
- }
-
- private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
- if(!isConnected){
- try {
- int i = (int) (Math.random()*999)+11;
- username = "Xin"+ i ;
- jTextField1.setText(username);
- jTextField1.setEditable(false);
- socket = new Socket( IP , port );
- out = new PrintWriter(socket.getOutputStream(),true);
- in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- out.println(username + ":"+"已加入聊天"+ ":連接");
- isConnected = true;
-
- } catch (IOException ex) {
- JOptionPane.showMessageDialog(null , "沒連接到伺服器 再試一次.... \n");
- jTextField1.setEditable(false);
- }
- IncomingReader();
- }else{
- JOptionPane.showMessageDialog(null , "你已經登入了 \n" , "訊息" , JOptionPane.QUESTION_MESSAGE);
- }
- }
-
- public void sendExit() {
- String bye = (username + ":已經離開聊天:離開");
- try
- {
- out.println(bye);
-
- } catch (Exception e)
- {
- JOptionPane.showMessageDialog(null , "再試一次\n", "訊息" , JOptionPane.QUESTION_MESSAGE);
- }
- }
- public void Disconnect(){
- try
- {
- JOptionPane.showMessageDialog(null , "已經離開聊天");
- socket.close();
- } catch(Exception ex) {
- JOptionPane.showMessageDialog(null ,"失敗訊息", "訊息" , JOptionPane.ERROR_MESSAGE );
- }
- isConnected = false;
- jTextField1.setEditable(true);
-
- }
- private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
- sendExit();
- Disconnect();
- }
-
- private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
- String mess = "";
- if(jTextField2.getText().equals(mess)){
- jTextField2.setText("");
- }else{
- try {
- out.println(username + ":" + jTextField2.getText() + ":" + "聊天");
- jTextField2.setText("");
-
- } catch (Exception ex) {
- JOptionPane.showMessageDialog(null, "無法寄送....", "訊息" , JOptionPane.ERROR_MESSAGE);
- }
- }
- jTextField2.requestFocus();
- }
- ImageIcon member = new ImageIcon("MEMBER.png");
- private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
- String Users = "";
- for(String user : users )
- Users+=user+"\n";
- JOptionPane.showMessageDialog(null, Users, "在線成員", JOptionPane.QUESTION_MESSAGE , member);
- }
-
-
-
-
- public static void main(String args[]) {
-
-
-
-
-
- try {
- for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
- if ("Nimbus".equals(info.getName())) {
- javax.swing.UIManager.setLookAndFeel(info.getClassName());
- break;
- }
- }
- } catch (ClassNotFoundException ex) {
- java.util.logging.Logger.getLogger(Clinet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (InstantiationException ex) {
- java.util.logging.Logger.getLogger(Clinet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (IllegalAccessException ex) {
- java.util.logging.Logger.getLogger(Clinet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- } catch (javax.swing.UnsupportedLookAndFeelException ex) {
- java.util.logging.Logger.getLogger(Clinet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
- }
-
-
-
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new Clinet().setVisible(true);
- }
- });
- }
-
-
- private javax.swing.JButton jButton1;
- private javax.swing.JButton jButton2;
- private javax.swing.JButton jButton3;
- private javax.swing.JButton jButton4;
- private javax.swing.JButton jButton5;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JLabel jLabel2;
- private javax.swing.JScrollPane jScrollPane1;
- private javax.swing.JTextArea jTextArea1;
- private javax.swing.JTextField jTextField1;
- private javax.swing.JTextField jTextField2;
-
- }