程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 基於java編寫局域網多人聊天室

基於java編寫局域網多人聊天室

編輯:關於JAVA

基於java編寫局域網多人聊天室。本站提示廣大學習愛好者:(基於java編寫局域網多人聊天室)文章只能為提供參考,不一定能成為您想要的結果。以下是基於java編寫局域網多人聊天室正文


因為須要制造收集盤算機收集課程設計,而且不想弄收集布線或許局域網路由器設置裝備擺設等等這類完整弄不懂的器械,最初決議應用socket基於java編寫一個局域網聊天室:

關於socket和收集編程的相干常識詳見我另外一篇文章:Java基於socket編程

法式基於C/S構造,即客戶端辦事器形式。
辦事器:
默許ip為本機ip
須要兩邊肯定一個端標語
可設置最年夜銜接人數
可啟動與封閉
界面顯示在線用戶人和姓名(本機不在此顯示)
客戶端:
須要手動設置辦事器ip地址(局域網)
手動設置端標語
輸出姓名
可銜接可斷開
法式運轉界面以下:

辦事器:

客戶端:

詳細代碼我會在最初上傳。
軟件有許多缺乏,個中好比:
沒有與數據庫有任何交集
優化:可將一切用戶寄存在數據庫中,和將聊天記載也放入數據庫中
沒有完成一對一聊天
優化:需從新界說一對一聊天的辦法
還有很多缺乏的處所,往後有興致再回來漸漸研討

上面為該法式三個代碼:
User.java

public class User{
 /**
  * 用戶信息類
  * 用於記載用戶小我信息:姓名和IP
  */
 private String name;
 private String ip;

 public User(String name, String ip) {
  this.name = name;
  this.ip = ip;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getIp() {
  return ip;
 }
 public void setIp(String ip) {
  this.ip = ip;
 }
}

Server_more.java

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

public class Server_more {

 private JFrame frame;
 private JTextArea contentArea; //文本域
 private JTextField txt_message; //用於顯示文本信息
 private JTextField txt_max;  //設置最年夜銜接人數
 private JTextField txt_port; //設置端標語
 private JButton btn_start;  //開端按鈕
 private JButton btn_stop;  //斷開按鈕
 private JButton btn_send;  //發送按鈕
 private JPanel northPanel;  //南方面板
 private JPanel southPanel;  //南邊面板
 private JScrollPane rightPanel; //右邊轉動條
 private JScrollPane leftPanel; //左邊轉動條
 private JSplitPane centerSplit; //朋分線
 private JList userList;   //列表組件
 private DefaultListModel listModel;

 private ServerSocket serverSocket;
 private ServerThread serverThread;
 private ArrayList<ClientThread> clients;

 private boolean isStart = false;

 // 主辦法,法式履行進口
 public static void main(String[] args) {
  new Server_more();
 }

 // 履行新聞發送
 public void send() {
  if (!isStart) {
   JOptionPane.showMessageDialog(frame, "辦事器還未啟動,不克不及發送新聞!", "毛病",
     JOptionPane.ERROR_MESSAGE);
   return;
  }
  if (clients.size() == 0) {
   JOptionPane.showMessageDialog(frame, "沒有效戶在線,不克不及發送新聞!", "毛病",
     JOptionPane.ERROR_MESSAGE);
   return;
  }
  String message = txt_message.getText().trim();
  if (message == null || message.equals("")) {
   JOptionPane.showMessageDialog(frame, "新聞不克不及為空!", "毛病",
     JOptionPane.ERROR_MESSAGE);
   return;
  }
  sendServerMessage(message);// 群發辦事器新聞
  contentArea.append("辦事器:" + txt_message.getText() + "\r\n");
  txt_message.setText(null);
 }

 // 結構放法
 public Server_more() {
  frame = new JFrame("辦事器");
  // 更改JFrame的圖標:
  //frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png")));
  //frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Server.class.getResource("qq.png")));
  contentArea = new JTextArea();
  contentArea.setEditable(false);
  contentArea.setForeground(Color.blue);
  txt_message = new JTextField();
  txt_max = new JTextField("30");
  txt_port = new JTextField("6666");
  btn_start = new JButton("啟動");
  btn_stop = new JButton("停滯");
  btn_send = new JButton("發送");
  btn_stop.setEnabled(false);
  listModel = new DefaultListModel();
  userList = new JList(listModel);

  southPanel = new JPanel(new BorderLayout());
  southPanel.setBorder(new TitledBorder("寫新聞"));
  southPanel.add(txt_message, "Center");
  southPanel.add(btn_send, "East");
  leftPanel = new JScrollPane(userList);
  leftPanel.setBorder(new TitledBorder("在線用戶"));

  rightPanel = new JScrollPane(contentArea);
  rightPanel.setBorder(new TitledBorder("新聞顯示區"));

  centerSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel,
    rightPanel);
  centerSplit.setDividerLocation(100);
  northPanel = new JPanel();
  northPanel.setLayout(new GridLayout(1, 6));
  northPanel.add(new JLabel("人數下限"));
  northPanel.add(txt_max);
  northPanel.add(new JLabel("端口"));
  northPanel.add(txt_port);
  northPanel.add(btn_start);
  northPanel.add(btn_stop);
  northPanel.setBorder(new TitledBorder("設置裝備擺設信息"));

  frame.setLayout(new BorderLayout());
  frame.add(northPanel, "North");
  frame.add(centerSplit, "Center");
  frame.add(southPanel, "South");
  frame.setSize(600, 400);
  //frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());//設置全屏
  int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;
  int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height;
  frame.setLocation((screen_width - frame.getWidth()) / 2,
    (screen_height - frame.getHeight()) / 2);
  frame.setVisible(true);

  // 封閉窗口時勢件
  frame.addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent e) {
    if (isStart) {
     closeServer();// 封閉辦事器
    }
    System.exit(0);// 加入法式
   }
  });

  // 文本框按回車鍵時勢件
  txt_message.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    send();
   }
  });

  // 單擊發送按鈕時勢件
  btn_send.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    send();
   }
  });

  // 單擊啟動辦事器按鈕時勢件
  btn_start.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (isStart) {
     JOptionPane.showMessageDialog(frame, "辦事器已處於啟動狀況,不要反復啟動!",
       "毛病", JOptionPane.ERROR_MESSAGE);
     return;
    }
    int max;
    int port;
    try {
     try {
      max = Integer.parseInt(txt_max.getText());
     } catch (Exception e1) {
      throw new Exception("人數下限為正整數!");
     }
     if (max <= 0) {
      throw new Exception("人數下限為正整數!");
     }
     try {
      port = Integer.parseInt(txt_port.getText());
     } catch (Exception e1) {
      throw new Exception("端標語為正整數!");
     }
     if (port <= 0) {
      throw new Exception("端標語 為正整數!");
     }
     serverStart(max, port);
     contentArea.append("辦事器已勝利啟動!人數下限:" + max + ",端口:" + port
       + "\r\n");
     JOptionPane.showMessageDialog(frame, "辦事器勝利啟動!");
     btn_start.setEnabled(false);
     txt_max.setEnabled(false);
     txt_port.setEnabled(false);
     btn_stop.setEnabled(true);
    } catch (Exception exc) {
     JOptionPane.showMessageDialog(frame, exc.getMessage(),
       "毛病", JOptionPane.ERROR_MESSAGE);
    }
   }
  });

  // 單擊停滯辦事器按鈕時勢件
  btn_stop.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (!isStart) {
     JOptionPane.showMessageDialog(frame, "辦事器還未啟動,無需停滯!", "毛病",
       JOptionPane.ERROR_MESSAGE);
     return;
    }
    try {
     closeServer();
     btn_start.setEnabled(true);
     txt_max.setEnabled(true);
     txt_port.setEnabled(true);
     btn_stop.setEnabled(false);
     contentArea.append("辦事器勝利停滯!\r\n");
     JOptionPane.showMessageDialog(frame, "辦事器勝利停滯!");
    } catch (Exception exc) {
     JOptionPane.showMessageDialog(frame, "停滯辦事器產生異常!", "毛病",
       JOptionPane.ERROR_MESSAGE);
    }
   }
  });
 }

 // 啟動辦事器
 public void serverStart(int max, int port) throws java.net.BindException {
  try {
   clients = new ArrayList<ClientThread>();
   serverSocket = new ServerSocket(port);
   serverThread = new ServerThread(serverSocket, max);
   serverThread.start();
   isStart = true;
  } catch (BindException e) {
   isStart = false;
   throw new BindException("端標語已被占用,請換一個!");
  } catch (Exception e1) {
   e1.printStackTrace();
   isStart = false;
   throw new BindException("啟動辦事器異常!");
  }
 }

 // 封閉辦事器
 @SuppressWarnings("deprecation")
 public void closeServer() {
  try {
   if (serverThread != null)
    serverThread.stop();// 停滯辦事器線程

   for (int i = clients.size() - 1; i >= 0; i--) {
    // 給一切在線用戶發送封閉敕令
    clients.get(i).getWriter().println("CLOSE");
    clients.get(i).getWriter().flush();
    // 釋放資本
    clients.get(i).stop();// 停滯此條為客戶端辦事的線程
    clients.get(i).reader.close();
    clients.get(i).writer.close();
    clients.get(i).socket.close();
    clients.remove(i);
   }
   if (serverSocket != null) {
    serverSocket.close();// 封閉辦事器端銜接
   }
   listModel.removeAllElements();// 清空用戶列表
   isStart = false;
  } catch (IOException e) {
   e.printStackTrace();
   isStart = true;
  }
 }

 // 群發辦事器新聞
 public void sendServerMessage(String message) {
  for (int i = clients.size() - 1; i >= 0; i--) {
   clients.get(i).getWriter().println("辦事器:" + message + "(多人發送)");
   clients.get(i).getWriter().flush();
  }
 }

 // 辦事器線程
 class ServerThread extends Thread {
  private ServerSocket serverSocket;
  private int max;// 人數下限

  // 辦事器線程的結構辦法
  public ServerThread(ServerSocket serverSocket, int max) {
   this.serverSocket = serverSocket;
   this.max = max;
  }

  public void run() {
   while (true) {// 一直的期待客戶真個鏈接
    try {
     Socket socket = serverSocket.accept();
     if (clients.size() == max) {// 假如已達人數下限
      BufferedReader r = new BufferedReader(
        new InputStreamReader(socket.getInputStream()));
      PrintWriter w = new PrintWriter(socket
        .getOutputStream());
      // 吸收客戶真個根本用戶信息
      String inf = r.readLine();
      StringTokenizer st = new StringTokenizer(inf, "@");
      User user = new User(st.nextToken(), st.nextToken());
      // 反應銜接勝利信息
      w.println("MAX@辦事器:對不起," + user.getName()
        + user.getIp() + ",辦事器在耳目數已達下限,請稍後測驗考試銜接!");
      w.flush();
      // 釋放資本
      r.close();
      w.close();
      socket.close();
      continue;
     }
     ClientThread client = new ClientThread(socket);
     client.start();// 開啟對此客戶端辦事的線程
     clients.add(client);
     listModel.addElement(client.getUser().getName());// 更新在線列表
     contentArea.append(client.getUser().getName()
       + client.getUser().getIp() + "上線!\r\n");
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 // 為一個客戶端辦事的線程
 class ClientThread extends Thread {
  private Socket socket;
  private BufferedReader reader;
  private PrintWriter writer;
  private User user;

  public BufferedReader getReader() {
   return reader;
  }

  public PrintWriter getWriter() {
   return writer;
  }

  public User getUser() {
   return user;
  }

  // 客戶端線程的結構辦法
  public ClientThread(Socket socket) {
   try {
    this.socket = socket;
    reader = new BufferedReader(new InputStreamReader(socket
      .getInputStream()));
    writer = new PrintWriter(socket.getOutputStream());
    // 吸收客戶真個根本用戶信息
    String inf = reader.readLine();
    StringTokenizer st = new StringTokenizer(inf, "@");
    user = new User(st.nextToken(), st.nextToken());
    // 反應銜接勝利信息
    writer.println(user.getName() + user.getIp() + "與辦事器銜接勝利!");
    writer.flush();
    // 反應以後在線用戶信息
    if (clients.size() > 0) {
     String temp = "";
     for (int i = clients.size() - 1; i >= 0; i--) {
      temp += (clients.get(i).getUser().getName() + "/" + clients
        .get(i).getUser().getIp())
        + "@";
     }
     writer.println("USERLIST@" + clients.size() + "@" + temp);
     writer.flush();
    }
    // 向一切在線用戶發送該用戶上線敕令
    for (int i = clients.size() - 1; i >= 0; i--) {
     clients.get(i).getWriter().println(
       "ADD@" + user.getName() + user.getIp());
     clients.get(i).getWriter().flush();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  @SuppressWarnings("deprecation")
  public void run() {// 赓續吸收客戶真個新聞,停止處置。
   String message = null;
   while (true) {
    try {
     message = reader.readLine();// 吸收客戶端新聞
     if (message.equals("CLOSE"))// 下線敕令
     {
      contentArea.append(this.getUser().getName()
        + this.getUser().getIp() + "下線!\r\n");
      // 斷開銜接釋放資本
      reader.close();
      writer.close();
      socket.close();

      // 向一切在線用戶發送該用戶的下線敕令
      for (int i = clients.size() - 1; i >= 0; i--) {
       clients.get(i).getWriter().println(
         "DELETE@" + user.getName());
       clients.get(i).getWriter().flush();
      }

      listModel.removeElement(user.getName());// 更新在線列表

      // 刪除此條客戶端辦事線程
      for (int i = clients.size() - 1; i >= 0; i--) {
       if (clients.get(i).getUser() == user) {
        ClientThread temp = clients.get(i);
        clients.remove(i);// 刪除此用戶的辦事線程
        temp.stop();// 停滯這條辦事線程
        return;
       }
      }
     } else {
      dispatcherMessage(message);// 轉發新聞
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }

  // 轉發新聞
  public void dispatcherMessage(String message) {
   StringTokenizer stringTokenizer = new StringTokenizer(message, "@");
   String source = stringTokenizer.nextToken();
   String owner = stringTokenizer.nextToken();
   String content = stringTokenizer.nextToken();
   message = source + ":" + content;
   contentArea.append(message + "\r\n");
   if (owner.equals("ALL")) {// 群發
    for (int i = clients.size() - 1; i >= 0; i--) {
     clients.get(i).getWriter().println(message + "(多人發送)");
     clients.get(i).getWriter().flush();
    }
   }
  }
 }
}

Client_more.java

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

public class Client_more{

 private JFrame frame;
 private JList userList;
 private JTextArea textArea;
 private JTextField textField;
 private JTextField txt_port;
 private JTextField txt_hostIp;
 private JTextField txt_name;
 private JButton btn_start;
 private JButton btn_stop;
 private JButton btn_send;
 private JPanel northPanel;
 private JPanel southPanel;
 private JScrollPane rightScroll;
 private JScrollPane leftScroll;
 private JSplitPane centerSplit;

 private DefaultListModel listModel;
 private boolean isConnected = false;

 private Socket socket;
 private PrintWriter writer;
 private BufferedReader reader;
 private MessageThread messageThread;// 擔任吸收新聞的線程
 private Map<String, User> onLineUsers = new HashMap<String, User>();// 一切在線用戶

 // 主辦法,法式進口
 public static void main(String[] args) {
  new Client_more();
 }

 // 履行發送
 public void send() {
  if (!isConnected) {
   JOptionPane.showMessageDialog(frame, "還沒有銜接辦事器,沒法發送新聞!", "毛病",
     JOptionPane.ERROR_MESSAGE);
   return;
  }
  String message = textField.getText().trim();
  if (message == null || message.equals("")) {
   JOptionPane.showMessageDialog(frame, "新聞不克不及為空!", "毛病",
     JOptionPane.ERROR_MESSAGE);
   return;
  }
  sendMessage(frame.getTitle() + "@" + "ALL" + "@" + message);
  textField.setText(null);
 }

 // 結構辦法
 public Client_more() {
  textArea = new JTextArea();
  textArea.setEditable(false);
  textArea.setForeground(Color.blue);
  textField = new JTextField();
  txt_port = new JTextField("6666");
  txt_hostIp = new JTextField("127.0.0.1");
  txt_name = new JTextField("吳承潛");
  btn_start = new JButton("銜接");
  btn_stop = new JButton("斷開");
  btn_send = new JButton("發送");
  listModel = new DefaultListModel();
  userList = new JList(listModel);

  northPanel = new JPanel();
  northPanel.setLayout(new GridLayout(1, 7));
  northPanel.add(new JLabel("端口"));
  northPanel.add(txt_port);
  northPanel.add(new JLabel("辦事器IP"));
  northPanel.add(txt_hostIp);
  northPanel.add(new JLabel("姓名"));
  northPanel.add(txt_name);
  northPanel.add(btn_start);
  northPanel.add(btn_stop);
  northPanel.setBorder(new TitledBorder("銜接信息"));

  rightScroll = new JScrollPane(textArea);
  rightScroll.setBorder(new TitledBorder("新聞顯示區"));
  leftScroll = new JScrollPane(userList);
  leftScroll.setBorder(new TitledBorder("在線用戶"));
  southPanel = new JPanel(new BorderLayout());
  southPanel.add(textField, "Center");
  southPanel.add(btn_send, "East");
  southPanel.setBorder(new TitledBorder("寫新聞"));

  centerSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScroll,
    rightScroll);
  centerSplit.setDividerLocation(100);

  frame = new JFrame("客戶機");
  // 更改JFrame的圖標:
 // frame.setIconImage(Toolkit.getDefaultToolkit().createImage(Client.class.getResource("qq.png")));
  frame.setLayout(new BorderLayout());
  frame.add(northPanel, "North");
  frame.add(centerSplit, "Center");
  frame.add(southPanel, "South");
  frame.setSize(600, 400);
  int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;
  int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height;
  frame.setLocation((screen_width - frame.getWidth()) / 2,
    (screen_height - frame.getHeight()) / 2);
  frame.setVisible(true);

  // 寫新聞的文本框中按回車鍵時勢件
  textField.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    send();
   }
  });

  // 單擊發送按鈕時勢件
  btn_send.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    send();
   }
  });

  // 單擊銜接按鈕時勢件
  btn_start.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    int port;
    if (isConnected) {
     JOptionPane.showMessageDialog(frame, "已處於銜接上狀況,不要反復銜接!",
       "毛病", JOptionPane.ERROR_MESSAGE);
     return;
    }
    try {
     try {
      port = Integer.parseInt(txt_port.getText().trim());
     } catch (NumberFormatException e2) {
      throw new Exception("端標語不相符請求!端口為整數!");
     }
     String hostIp = txt_hostIp.getText().trim();
     String name = txt_name.getText().trim();
     if (name.equals("") || hostIp.equals("")) {
      throw new Exception("姓名、辦事器IP不克不及為空!");
     }
     boolean flag = connectServer(port, hostIp, name);
     if (flag == false) {
      throw new Exception("與辦事器銜接掉敗!");
     }
     frame.setTitle(name);
     JOptionPane.showMessageDialog(frame, "勝利銜接!");
    } catch (Exception exc) {
     JOptionPane.showMessageDialog(frame, exc.getMessage(),
       "毛病", JOptionPane.ERROR_MESSAGE);
    }
   }
  });

  // 單擊斷開按鈕時勢件
  btn_stop.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (!isConnected) {
     JOptionPane.showMessageDialog(frame, "已處於斷開狀況,不要反復斷開!",
       "毛病", JOptionPane.ERROR_MESSAGE);
     return;
    }
    try {
     boolean flag = closeConnection();// 斷開銜接
     if (flag == false) {
      throw new Exception("斷開銜接產生異常!");
     }
     JOptionPane.showMessageDialog(frame, "勝利斷開!");
    } catch (Exception exc) {
     JOptionPane.showMessageDialog(frame, exc.getMessage(),
       "毛病", JOptionPane.ERROR_MESSAGE);
    }
   }
  });

  // 封閉窗口時勢件
  frame.addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent e) {
    if (isConnected) {
     closeConnection();// 封閉銜接
    }
    System.exit(0);// 加入法式
   }
  });
 }

 /**
  * 銜接辦事器
  * 
  * @param port
  * @param hostIp
  * @param name
  */
 public boolean connectServer(int port, String hostIp, String name) {
  // 銜接辦事器
  try {
   socket = new Socket(hostIp, port);// 依據端標語和辦事器ip樹立銜接
   writer = new PrintWriter(socket.getOutputStream());
   reader = new BufferedReader(new InputStreamReader(socket
     .getInputStream()));
   // 發送客戶端用戶根本信息(用戶名和ip地址)
   sendMessage(name + "@" + socket.getLocalAddress().toString());
   // 開啟吸收新聞的線程
   messageThread = new MessageThread(reader, textArea);
   messageThread.start();
   isConnected = true;// 曾經銜接上了
   return true;
  } catch (Exception e) {
   textArea.append("與端標語為:" + port + " IP地址為:" + hostIp
     + " 的辦事器銜接掉敗!" + "\r\n");
   isConnected = false;// 未銜接上
   return false;
  }
 }

 /**
  * 發送新聞
  * 
  * @param message
  */
 public void sendMessage(String message) {
  writer.println(message);
  writer.flush();
 }

 /**
  * 客戶端自動封閉銜接
  */
 @SuppressWarnings("deprecation")
 public synchronized boolean closeConnection() {
  try {
   sendMessage("CLOSE");// 發送斷開銜接敕令給辦事器
   messageThread.stop();// 停滯接收新聞線程
   // 釋放資本
   if (reader != null) {
    reader.close();
   }
   if (writer != null) {
    writer.close();
   }
   if (socket != null) {
    socket.close();
   }
   isConnected = false;
   return true;
  } catch (IOException e1) {
   e1.printStackTrace();
   isConnected = true;
   return false;
  }
 }

 // 赓續吸收新聞的線程
 class MessageThread extends Thread {
  private BufferedReader reader;
  private JTextArea textArea;

  // 吸收新聞線程的結構辦法
  public MessageThread(BufferedReader reader, JTextArea textArea) {
   this.reader = reader;
   this.textArea = textArea;
  }

  // 主動的封閉銜接
  public synchronized void closeCon() throws Exception {
   // 清空用戶列表
   listModel.removeAllElements();
   // 主動的封閉銜接釋放資本
   if (reader != null) {
    reader.close();
   }
   if (writer != null) {
    writer.close();
   }
   if (socket != null) {
    socket.close();
   }
   isConnected = false;// 修正狀況為斷開
  }

  public void run() {
   String message = "";
   while (true) {
    try {
     message = reader.readLine();
     StringTokenizer stringTokenizer = new StringTokenizer(
       message, "/@");
     String command = stringTokenizer.nextToken();// 敕令
     if (command.equals("CLOSE"))// 辦事器已封閉敕令
     {
      textArea.append("辦事器已封閉!\r\n");
      closeCon();// 主動的封閉銜接
      return;// 停止線程
     } else if (command.equals("ADD")) {// 有效戶上線更新在線列表
      String username = "";
      String userIp = "";
      if ((username = stringTokenizer.nextToken()) != null
        && (userIp = stringTokenizer.nextToken()) != null) {
       User user = new User(username, userIp);
       onLineUsers.put(username, user);
       listModel.addElement(username);
      }
     } else if (command.equals("DELETE")) {// 有效戶下線更新在線列表
      String username = stringTokenizer.nextToken();
      User user = (User) onLineUsers.get(username);
      onLineUsers.remove(user);
      listModel.removeElement(username);
     } else if (command.equals("USERLIST")) {// 加載在線用戶列表
      int size = Integer
        .parseInt(stringTokenizer.nextToken());
      String username = null;
      String userIp = null;
      for (int i = 0; i < size; i++) {
       username = stringTokenizer.nextToken();
       userIp = stringTokenizer.nextToken();
       User user = new User(username, userIp);
       onLineUsers.put(username, user);
       listModel.addElement(username);
      }
     } else if (command.equals("MAX")) {// 人數已達下限
      textArea.append(stringTokenizer.nextToken()
        + stringTokenizer.nextToken() + "\r\n");
      closeCon();// 主動的封閉銜接
      JOptionPane.showMessageDialog(frame, "辦事器緩沖區已滿!", "毛病",
        JOptionPane.ERROR_MESSAGE);
      return;// 停止線程
     } else {// 通俗新聞
      textArea.append(message + "\r\n");
     }
    } catch (IOException e) {
     e.printStackTrace();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }
}

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved