| 1 | import java.net.*; |
| 2 | import java.io.*; |
| 3 | import java.util.*; |
| 4 | |
| 5 | public class BroadcastThreadService implements Runnable { |
| 6 | |
| 7 | private Socket clientSocket; |
| 8 | private static ArrayList<PrintWriter> listWriter; |
| 9 | |
| 10 | BroadcastThreadService(Socket clientSocket) { |
| 11 | System.out.println("Creation d'un thread pour repondre a un client, port " |
| 12 | + clientSocket.getPort()); |
| 13 | this.clientSocket = clientSocket; |
| 14 | if (listWriter == null) |
| 15 | listWriter = new ArrayList<PrintWriter>(); |
| 16 | } |
| 17 | |
| 18 | public void run() { |
| 19 | try { |
| 20 | doService(clientSocket, listWriter); |
| 21 | clientSocket.close(); |
| 22 | } catch (IOException e) { |
| 23 | System.err.println("IOException : " + e); |
| 24 | e.printStackTrace(); |
| 25 | } |
| 26 | finally { |
| 27 | try { |
| 28 | if (this.clientSocket != null) |
| 29 | this.clientSocket.close(); |
| 30 | } catch (IOException e) { |
| 31 | System.err.println("IOException : " + e); |
| 32 | e.printStackTrace(); |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException { |
| 38 | BufferedReader in; |
| 39 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); |
| 40 | PrintWriter OWriter = new PrintWriter(clientSocket.getOutputStream()); |
| 41 | sharedList.add(OWriter); |
| 42 | boolean end = false; |
| 43 | while (!end) { |
| 44 | String theLine = in.readLine(); |
| 45 | if (theLine.equals(".")) { |
| 46 | end = true; // le thread de service doit terminer |
| 47 | break; // do not broadcast the dot that will close clients threads |
| 48 | } |
| 49 | broadcastMsg(theLine); |
| 50 | } |
| 51 | sharedList.remove(OWriter); |
| 52 | if (in != null) |
| 53 | in.close(); |
| 54 | if (OWriter != null) |
| 55 | OWriter.close(); |
| 56 | System.out.println("Fin du thread repondant au client, port " |
| 57 | + clientSocket.getPort()); |
| 58 | } |
| 59 | |
| 60 | private void broadcastMsg(String msg) { |
| 61 | ListIterator<PrintWriter> iter = listWriter.listIterator(); |
| 62 | while (iter.hasNext()) { |
| 63 | PrintWriter cursorPW = iter.next(); |
| 64 | cursorPW.println(msg); |
| 65 | cursorPW.flush(); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | } |