fd05e176447fa230421792430274ec96fcecc80d
[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 broadcastMsg(theLine);
58 }
59 sharedList.remove(OWriter);
60 if (OWriter != null)
61 OWriter.close();
62 if (in != null)
63 in.close();
64 System.out.println("Fin du thread repondant au client, port "
65 + clientSocket.getPort());
66 }
67
68 private void broadcastMsg(String msg) {
69 ListIterator<PrintWriter> iter = listWriter.listIterator();
70 while (iter.hasNext()) {
71 PrintWriter cursorPW = iter.next();
72 cursorPW.println(msg);
73 cursorPW.flush();
74 }
75 }
76
77 }