1 回答

TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
非常簡(jiǎn)單的決定創(chuàng)建一個(gè)像列表一樣的 PrintWriter 持有者。不要忘記為此系列創(chuàng)建關(guān)閉機(jī)制!并考慮多線程。
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();
}
}
}
如果它是一個(gè)大項(xiàng)目,最好為消息創(chuàng)建隊(duì)列
添加回答
舉報(bào)