TD2: Fix the remaining bugs in the IHM chat client.
[TD_SR.git] / TD2 / server / BroadcastThreadService.java
CommitLineData
b1bd144d
JB
1import java.net.*;
2import java.io.*;
3import java.util.*;
4
b9a33c97 5public 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 21 clientSocket.close();
b349a9de
JB
22 }
23 catch (IOException e) {
b1bd144d
JB
24 System.err.println("IOException : " + e);
25 e.printStackTrace();
26 }
27 finally {
28 try {
29 if (this.clientSocket != null)
30 this.clientSocket.close();
b349a9de
JB
31 }
32 catch (IOException e) {
b1bd144d
JB
33 System.err.println("IOException : " + e);
34 e.printStackTrace();
35 }
36 }
37 }
38
da31e6da
JB
39 /**
40 * Be careful, this function must be thread-safe
41 * @param clientSocket [description]
42 * @param sharedList [description]
43 * @throws IOException [description]
44 */
b9a33c97 45 public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException {
c4d2497c 46 PrintWriter OWriter = new PrintWriter(clientSocket.getOutputStream());
b1bd144d 47 BufferedReader in;
b1bd144d 48 in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
b483402f 49 sharedList.add(OWriter);
b1bd144d
JB
50 boolean end = false;
51 while (!end) {
52 String theLine = in.readLine();
b483402f 53 if (theLine.equals(".")) {
b1bd144d 54 end = true; // le thread de service doit terminer
da31e6da 55 break; // do not broadcast the dot that will close all clients threads
b483402f 56 }
92d3f605 57 System.out.println("Broadcasting the message \"" + theLine + "\" received from " + clientSocket.toString());
b9a33c97 58 broadcastMsg(theLine);
b1bd144d 59 }
b483402f 60 sharedList.remove(OWriter);
b483402f
JB
61 if (OWriter != null)
62 OWriter.close();
c4d2497c
JB
63 if (in != null)
64 in.close();
b1bd144d
JB
65 System.out.println("Fin du thread repondant au client, port "
66 + clientSocket.getPort());
67 }
68
b9a33c97
JB
69 private void broadcastMsg(String msg) {
70 ListIterator<PrintWriter> iter = listWriter.listIterator();
71 while (iter.hasNext()) {
72 PrintWriter cursorPW = iter.next();
73 cursorPW.println(msg);
74 cursorPW.flush();
b1bd144d 75 }
b1bd144d
JB
76 }
77
78}