1 回答

TA貢獻1893條經驗 獲得超10個贊
非常簡單的決定創建一個像列表一樣的 PrintWriter 持有者。不要忘記為此系列創建關閉機制!并考慮多線程。
public class ServerThread extends Thread {
private final Socket socket;
private final List<PrintWriter> outs;
public ServerThread(Socket socket, List<PrintWriter> outs) {
super("ServerThread");
this.socket = socket;
this.outs = outs;
System.out.println("Opened outs: " + outs.size());
}
private void sendToAll(String msg) throws IOException {
for(PrintWriter out: outs) {
out.println(msg);
}
}
public void run() {
try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
System.out.println("stream opened");
outs.add(out);
String getMSGs;
while((getMSGs = in.readLine()) != null) {
System.out.println("msg received and sent " + getMSGs);
sendToAll(getMSGs);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果它是一個大項目,最好為消息創建隊列
添加回答
舉報