JAVA線上聊天室
阿新 • • 發佈:2018-12-27
聊天室服務端:
/** * 線上聊天室:服務端 * 使用多執行緒實現多個客戶可以正常收發多條資訊 * @author fujun * */ public class Chat{ public static void main(String[] args) throws Exception { System.out.println("---Server----"); // 1、指定埠使用ServerSocket ServerSocket socket = new ServerSocket(8888); while(true) // 2、阻塞式等待連線accept Socket server = socket.accept(); System.out.println("一個客戶端建立連線"); new Thread(()->{ // 3、接收訊息 DataInputStream dis = null; DataOutputStream dos = null; try{ dis = new DataInputStream(server.getInputStream()); dos = new DataOutputStream(server.getOutputStream()); }catch (IOException e1) { e1.printStackTrace(); } boolean isRunning = true; while(isRunning ){ String msg; try{ mag = = dis.readUTF(); // 4、返回訊息 dos.writeUTF(msg); // 釋放資源 dos.flush(); }catch(IOException e){ // 停止執行緒 isRunning = false; } } try{ dos.close(); dis.close(); server.close(); }catch(IOException e){ e.printStackTrace(); } }).start(); } } }
聊天室客戶端保持不變!!
/** * 線上聊天室:客戶端 * 使用多執行緒實現多個客戶可以正常收發多條資訊 * @author fujun * */ public class TMultiClient { public static void main(String[] args) throws Exception { System.out.println("-----Clinet-----"); // 1、建立連線:使用Socket建立客戶端 + 服務端的地址和埠 Socket client = new Socket("localhost",8888); // 2、客戶端傳送訊息 BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream dos = new DataOutputStream(client.getOutputStream()); DataInputStream dis = new DataInputStream(client.getInputStream()); boolean isRunning = true; while(isRunning){ String msg = console.readLine(); dos.writeUTF(msg); dos.flush(); // 3、獲取訊息 msg = dis.readUTF(); System.out.println(msg); } // 釋放資源 dos.close(); dis.close(); client.close(); } }