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 JB |
20 | doService(clientSocket, listWriter); |
21 | //FIXME: also close the BR and PW? | |
b1bd144d | 22 | clientSocket.close(); |
b9a33c97 | 23 | //FIXME: remove the associated PW from the ArrayList |
b1bd144d JB |
24 | } catch (IOException e) { |
25 | System.err.println("IOException : " + e); | |
26 | e.printStackTrace(); | |
27 | } | |
28 | finally { | |
29 | try { | |
30 | if (this.clientSocket != null) | |
31 | this.clientSocket.close(); | |
32 | } catch (IOException e) { | |
33 | System.err.println("IOException : " + e); | |
34 | e.printStackTrace(); | |
35 | } | |
36 | } | |
37 | } | |
38 | ||
b9a33c97 | 39 | public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException { |
b1bd144d | 40 | BufferedReader in; |
b1bd144d | 41 | in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); |
b9a33c97 | 42 | sharedList.add(new PrintWriter(clientSocket.getOutputStream())); |
b1bd144d JB |
43 | boolean end = false; |
44 | while (!end) { | |
45 | String theLine = in.readLine(); | |
46 | if (theLine.equals(".")) | |
47 | end = true; // le thread de service doit terminer | |
b9a33c97 | 48 | broadcastMsg(theLine); |
b1bd144d JB |
49 | } |
50 | System.out.println("Fin du thread repondant au client, port " | |
51 | + clientSocket.getPort()); | |
52 | } | |
53 | ||
b9a33c97 JB |
54 | private void broadcastMsg(String msg) { |
55 | ListIterator<PrintWriter> iter = listWriter.listIterator(); | |
56 | while (iter.hasNext()) { | |
57 | PrintWriter cursorPW = iter.next(); | |
58 | cursorPW.println(msg); | |
59 | cursorPW.flush(); | |
b1bd144d | 60 | } |
b1bd144d JB |
61 | } |
62 | ||
63 | } |