TD2: Fix the remaining bugs in the IHM chat client.
[TD_SR.git] / TD2 / server / BroadcastoThreadService.java
CommitLineData
da31e6da
JB
1import java.net.*;
2import java.io.*;
3import java.util.*;
4
5public class BroadcastoThreadService implements Runnable {
6
7 private Socket clientSocket;
8 private static ArrayList<ObjectOutputStream> listoWriter;
9
10 BroadcastoThreadService(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 (listoWriter == null)
15 listoWriter = new ArrayList<ObjectOutputStream>();
16 }
17
18 public void run() {
19 try {
20 doService(clientSocket, listoWriter);
21 clientSocket.close();
b349a9de
JB
22 }
23 catch (IOException e) {
da31e6da
JB
24 System.err.println("IOException : " + e);
25 e.printStackTrace();
26 }
27 catch (ClassNotFoundException e) {
957ecace 28 System.err.println("ClassNotFoundException: " + e);
da31e6da
JB
29 e.printStackTrace();
30 }
31 finally {
32 try {
33 if (this.clientSocket != null)
34 this.clientSocket.close();
b349a9de
JB
35 }
36 catch (IOException e) {
da31e6da
JB
37 System.err.println("IOException : " + e);
38 e.printStackTrace();
39 }
40 }
41 }
42
3d59b440
JB
43 /**
44 * Be careful, this function must be thread-safe
45 * @param clientSocket [description]
46 * @param sharedList [description]
47 * @throws IOException [description]
48 * @throws ClassNotFoundException [description]
49 */
da31e6da 50 public void doService(Socket clientSocket, ArrayList<ObjectOutputStream> sharedList) throws IOException, ClassNotFoundException {
da31e6da 51 ObjectOutputStream OWriter = new ObjectOutputStream(clientSocket.getOutputStream());
c4d2497c 52 ObjectInputStream OReader = new ObjectInputStream(clientSocket.getInputStream());
da31e6da
JB
53 sharedList.add(OWriter);
54 boolean end = false;
55 while (!end) {
56 Message roMsg = (Message)OReader.readObject();
57 if (roMsg.getTexte().equals(".")) {
58 end = true; // le thread de service doit terminer
59 break; // do not broadcast the dot that will close all clients threads
60 }
92d3f605 61 System.out.println("Broadcasting the message \"" + roMsg + "\" received from " + clientSocket.toString());
da31e6da
JB
62 broadcastoMsg(roMsg);
63 }
64 sharedList.remove(OWriter);
da31e6da
JB
65 if (OWriter != null)
66 OWriter.close();
c4d2497c
JB
67 if (OReader != null)
68 OReader.close();
da31e6da
JB
69 System.out.println("Fin du thread repondant au client, port "
70 + clientSocket.getPort());
71 }
72
73 private void broadcastoMsg(Message oMsg) throws IOException, ClassNotFoundException {
74 ListIterator<ObjectOutputStream> iter = listoWriter.listIterator();
75 while (iter.hasNext()) {
76 ObjectOutputStream cursorOOS = iter.next();
77 cursorOOS.writeObject(oMsg);
78 cursorOOS.flush();
79 }
80 }
81
82}