import java.io.*;
import java.util.*;
-public class EchoServerThreadService implements Runnable {
+public class BroadcastThreadService implements Runnable {
private Socket clientSocket;
- private ArrayList<PrintWriter> listWriter;
+ private static ArrayList<PrintWriter> listWriter;
- EchoServerThreadService(Socket clientSocket) {
- System.out.println("Creation d'un thread pour repondre a un client, port " + clientSocket.getPort());
+ BroadcastThreadService(Socket clientSocket) {
+ System.out.println("Creation d'un thread pour repondre a un client, port "
+ + clientSocket.getPort());
this.clientSocket = clientSocket;
+ if (listWriter == null)
+ listWriter = new ArrayList<PrintWriter>();
}
public void run() {
try {
- doService(clientSocket);
+ doService(clientSocket, listWriter);
+ //FIXME: also close the BR and PW?
clientSocket.close();
+ //FIXME: remove the associated PW from the ArrayList
} catch (IOException e) {
System.err.println("IOException : " + e);
e.printStackTrace();
}
}
- public void doService(Socket clientSocket) throws IOException {
+ public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException {
BufferedReader in;
- PrintStream out;
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- out = new PrintStream(clientSocket.getOutputStream());
- //listWriter.add(new PrintWriter(clientSocket.getOutputStream()));
+ sharedList.add(new PrintWriter(clientSocket.getOutputStream()));
boolean end = false;
while (!end) {
String theLine = in.readLine();
if (theLine.equals("."))
end = true; // le thread de service doit terminer
- out.println(theLine);
+ broadcastMsg(theLine);
}
System.out.println("Fin du thread repondant au client, port "
+ clientSocket.getPort());
}
- public void broadcastMsg(String msg) {
- for (int i = 0; i < listWriter.size(); i++) {
- listWriter.get(i);
+ private void broadcastMsg(String msg) {
+ ListIterator<PrintWriter> iter = listWriter.listIterator();
+ while (iter.hasNext()) {
+ PrintWriter cursorPW = iter.next();
+ cursorPW.println(msg);
+ cursorPW.flush();
}
-
}
}