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
);
22 } catch (IOException e
) {
23 System
.err
.println("IOException : " + e
);
28 if (this.clientSocket
!= null)
29 this.clientSocket
.close();
30 } catch (IOException e
) {
31 System
.err
.println("IOException : " + e
);
38 * Be careful, this function must be thread-safe
39 * @param clientSocket [description]
40 * @param sharedList [description]
41 * @throws IOException [description]
43 public void doService(Socket clientSocket
, ArrayList
<PrintWriter
> sharedList
) throws IOException
{
45 in
= new BufferedReader(new InputStreamReader(clientSocket
.getInputStream()));
46 PrintWriter OWriter
= new PrintWriter(clientSocket
.getOutputStream());
47 sharedList
.add(OWriter
);
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
55 broadcastMsg(theLine
);
57 sharedList
.remove(OWriter
);
62 System
.out
.println("Fin du thread repondant au client, port "
63 + clientSocket
.getPort());
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
);