180f735b49fa442ed5982afa0a286d8c3f0ff879
[TD_SR.git] / TD2 / server / BroadcastThreadService.java
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 //FIXME: also close the BR and PW?
22 clientSocket.close();
23 //FIXME: remove the associated PW from the ArrayList
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
39 public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException {
40 BufferedReader in;
41 in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
42 sharedList.add(new PrintWriter(clientSocket.getOutputStream()));
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
48 broadcastMsg(theLine);
49 }
50 System.out.println("Fin du thread repondant au client, port "
51 + clientSocket.getPort());
52 }
53
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();
60 }
61 }
62
63 }