Commit | Line | Data |
---|---|---|
b1bd144d JB |
1 | import java.net.*; |
2 | import java.io.*; | |
3 | import java.util.*; | |
4 | ||
b9a33c97 | 5 | public class BroadcastThreadService implements Runnable { |
b1bd144d JB |
6 | |
7 | private Socket clientSocket; | |
b9a33c97 | 8 | private static ArrayList<PrintWriter> listWriter; |
b1bd144d | 9 | |
b9a33c97 JB |
10 | BroadcastThreadService(Socket clientSocket) { |
11 | System.out.println("Creation d'un thread pour repondre a un client, port " | |
12 | + clientSocket.getPort()); | |
b1bd144d | 13 | this.clientSocket = clientSocket; |
b9a33c97 JB |
14 | if (listWriter == null) |
15 | listWriter = new ArrayList<PrintWriter>(); | |
b1bd144d JB |
16 | } |
17 | ||
18 | public void run() { | |
19 | try { | |
b9a33c97 | 20 | doService(clientSocket, listWriter); |
b1bd144d JB |
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 | ||
b9a33c97 | 37 | public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException { |
b1bd144d | 38 | BufferedReader in; |
b1bd144d | 39 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); |
b483402f JB |
40 | PrintWriter OWriter = new PrintWriter(clientSocket.getOutputStream()); |
41 | sharedList.add(OWriter); | |
b1bd144d JB |
42 | boolean end = false; |
43 | while (!end) { | |
44 | String theLine = in.readLine(); | |
b483402f | 45 | if (theLine.equals(".")) { |
b1bd144d | 46 | end = true; // le thread de service doit terminer |
b483402f JB |
47 | break; // do not broadcast the dot that will close clients threads |
48 | } | |
b9a33c97 | 49 | broadcastMsg(theLine); |
b1bd144d | 50 | } |
b483402f JB |
51 | sharedList.remove(OWriter); |
52 | if (in != null) | |
53 | in.close(); | |
54 | if (OWriter != null) | |
55 | OWriter.close(); | |
b1bd144d JB |
56 | System.out.println("Fin du thread repondant au client, port " |
57 | + clientSocket.getPort()); | |
58 | } | |
59 | ||
b9a33c97 JB |
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(); | |
b1bd144d | 66 | } |
b1bd144d JB |
67 | } |
68 | ||
69 | } |