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