5 public class BroadcastThreadService
implements Runnable
{
7 private Socket clientSocket
;
8 private static ArrayList
<PrintWriter
> listWriter
;
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
>();
20 doService(clientSocket
, listWriter
);
23 catch (IOException e
) {
24 System
.err
.println("IOException : " + e
);
29 if (this.clientSocket
!= null)
30 this.clientSocket
.close();
32 catch (IOException e
) {
33 System
.err
.println("IOException : " + e
);
40 * Be careful, this function must be thread-safe
41 * @param clientSocket [description]
42 * @param sharedList [description]
43 * @throws IOException [description]
45 public void doService(Socket clientSocket
, ArrayList
<PrintWriter
> sharedList
) throws IOException
{
46 PrintWriter OWriter
= new PrintWriter(clientSocket
.getOutputStream());
48 in
= new BufferedReader(new InputStreamReader(clientSocket
.getInputStream()));
49 sharedList
.add(OWriter
);
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
57 System
.out
.println("Broadcasting the message \"" + theLine
+ "\" received from " + clientSocket
.toString());
58 broadcastMsg(theLine
);
60 sharedList
.remove(OWriter
);
65 System
.out
.println("Fin du thread repondant au client, port "
66 + clientSocket
.getPort());
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
);