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();
}
}
}
如果它是一个大项目,最好为消息创建队列
添加回答
举报