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 | ||
da31e6da JB |
37 | /** |
38 | * Be careful, this function must be thread-safe | |
39 | * @param clientSocket [description] | |
40 | * @param sharedList [description] | |
41 | * @throws IOException [description] | |
42 | */ | |
b9a33c97 | 43 | public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException { |
b1bd144d | 44 | BufferedReader in; |
b1bd144d | 45 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); |
b483402f JB |
46 | PrintWriter OWriter = new PrintWriter(clientSocket.getOutputStream()); |
47 | sharedList.add(OWriter); | |
b1bd144d JB |
48 | boolean end = false; |
49 | while (!end) { | |
50 | String theLine = in.readLine(); | |
b483402f | 51 | if (theLine.equals(".")) { |
b1bd144d | 52 | end = true; // le thread de service doit terminer |
da31e6da | 53 | break; // do not broadcast the dot that will close all clients threads |
b483402f | 54 | } |
b9a33c97 | 55 | broadcastMsg(theLine); |
b1bd144d | 56 | } |
b483402f JB |
57 | sharedList.remove(OWriter); |
58 | if (in != null) | |
59 | in.close(); | |
60 | if (OWriter != null) | |
61 | OWriter.close(); | |
b1bd144d JB |
62 | System.out.println("Fin du thread repondant au client, port " |
63 | + clientSocket.getPort()); | |
64 | } | |
65 | ||
b9a33c97 JB |
66 | private void broadcastMsg(String msg) { |
67 | ListIterator<PrintWriter> iter = listWriter.listIterator(); | |
68 | while (iter.hasNext()) { | |
69 | PrintWriter cursorPW = iter.next(); | |
70 | cursorPW.println(msg); | |
71 | cursorPW.flush(); | |
b1bd144d | 72 | } |
b1bd144d JB |
73 | } |
74 | ||
75 | } |