4bb29435b74ebcd62f554aa4399586cd209a513a
[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 }
23 catch (IOException e) {
24 System.err.println("IOException : " + e);
25 e.printStackTrace();
26 }
27 finally {
28 try {
29 if (this.clientSocket != null)
30 this.clientSocket.close();
31 }
32 catch (IOException e) {
33 System.err.println("IOException : " + e);
34 e.printStackTrace();
35 }
36 }
37 }
38
39 /**
40 * Be careful, this function must be thread-safe
41 * @param clientSocket [description]
42 * @param sharedList [description]
43 * @throws IOException [description]
44 */
45 public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException {
46 PrintWriter OWriter = new PrintWriter(clientSocket.getOutputStream());
47 BufferedReader in;
48 in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
49 sharedList.add(OWriter);
50 boolean end = false;
51 while (!end) {
52 String theLine = in.readLine();
53 if (theLine.equals(".")) {
54 end = true; // le thread de service doit terminer
55 break; // do not broadcast the dot that will close all clients threads
56 }
57 System.out.println("Broadcasting the message <" + theLine + "> received from " + clientSocket.toString());
58 broadcastMsg(theLine);
59 }
60 sharedList.remove(OWriter);
61 if (OWriter != null)
62 OWriter.close();
63 if (in != null)
64 in.close();
65 System.out.println("Fin du thread repondant au client, port "
66 + clientSocket.getPort());
67 }
68
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();
75 }
76 }
77
78 }