ServerSocket建立聊天室伺服器(二)
阿新 • • 發佈:2019-01-02
(平時操作,留下痕跡,以後效,君若受益,吾之大幸)
*編寫完伺服器,可開啟終端進行測試 開啟cmd 命令 鍵入 telnet localhost +(埠號)
例如:
回車 便與伺服器埠建立連線
一、MyServerSocket.class
package cn.upc.serversocket.main; public class MyServerSocket { public static void main(String[] args) { new ServerSocketListener().start(); System.out.println(1); } }
二、ServerSocketListener.class
package cn.upc.serversocket.main; import javax.swing.*; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketListener extends Thread { @Override public void run() { try { ServerSocket serverSocket = new ServerSocket(12345); //1~65535 while (true) { Socket socket = serverSocket.accept(); //監聽連線,建立連線,返回socket物件 //JOptionPane.showMessageDialog(null, "客戶端已經連線到12345埠"); ChatSocket cs = new ChatSocket(socket); cs.start(); ChatManager.getChatManager().add(cs); //新增至聊天管理器 } } catch (IOException e) { e.printStackTrace(); } } } 三、ChatSocket.class
package cn.upc.serversocket.main; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class ChatSocket extends Thread { Socket socket; public ChatSocket(Socket socket) { this.socket = socket; } public void out(String string) { //ServerSocket傳送資料功能 客戶端接收 try { socket.getOutputStream().write((string+"\n").getBytes("GBK")); } catch (IOException e) { ChatManager.getChatManager().remove(this); } } @Override public void run() { try { BufferedReader br = //ServerSocket接受資料功能 new BufferedReader( new InputStreamReader( socket.getInputStream(), "GBK")); String line = null; while ((line = br.readLine()) != null) { ChatManager.getChatManager().publish(this, line); //向各個客戶端傳送資料 } br.close(); } catch (IOException e) { System.out.println("斷開了一個客戶端連結"); ChatManager.getChatManager().remove(this); } } } 四、ChatManager.class
package cn.upc.serversocket.main;
import java.util.Vector;
public class ChatManager {
private ChatManager(){} //單例化
private static final ChatManager cm= new ChatManager();
public static ChatManager getChatManager(){
return cm;
}
Vector<ChatSocket> vector=new Vector<ChatSocket>();
public void add(ChatSocket cs){ //為集合新增socket物件
vector.add(cs);
}
public void remove(ChatSocket cs){
vector.remove(cs);
}
public void publish(ChatSocket cs,String string){ //某一執行緒 向其他執行緒釋出資訊
for (int i = 0; i < vector.size(); i++) {
ChatSocket chatSocket=vector.get(i);
if(!cs.equals(chatSocket)){
chatSocket.out(string);
}
}
}
}