TD2: Comment thread-safety requirement.
[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();
22 } catch (IOException e) {
23 System.err.println("IOException : " + e);
24 e.printStackTrace();
25 }
26 catch (ClassNotFoundException e) {
27 System.err.println("ClassNotFoundException: " + e);
28 e.printStackTrace();
29 }
30 finally {
31 try {
32 if (this.clientSocket != null)
33 this.clientSocket.close();
34 } catch (IOException e) {
35 System.err.println("IOException : " + e);
36 e.printStackTrace();
37 }
38 }
39 }
40
3d59b440
JB
41 /**
42 * Be careful, this function must be thread-safe
43 * @param clientSocket [description]
44 * @param sharedList [description]
45 * @throws IOException [description]
46 * @throws ClassNotFoundException [description]
47 */
da31e6da
JB
48 public void doService(Socket clientSocket, ArrayList<ObjectOutputStream> sharedList) throws IOException, ClassNotFoundException {
49 ObjectInputStream OReader = new ObjectInputStream(clientSocket.getInputStream());
50 ObjectOutputStream OWriter = new ObjectOutputStream(clientSocket.getOutputStream());
51 sharedList.add(OWriter);
52 boolean end = false;
53 while (!end) {
54 Message roMsg = (Message)OReader.readObject();
55 if (roMsg.getTexte().equals(".")) {
56 end = true; // le thread de service doit terminer
57 break; // do not broadcast the dot that will close all clients threads
58 }
59 broadcastoMsg(roMsg);
60 }
61 sharedList.remove(OWriter);
62 if (OReader != null)
63 OReader.close();
64 if (OWriter != null)
65 OWriter.close();
66 System.out.println("Fin du thread repondant au client, port "
67 + clientSocket.getPort());
68 }
69
70 private void broadcastoMsg(Message oMsg) throws IOException, ClassNotFoundException {
71 ListIterator<ObjectOutputStream> iter = listoWriter.listIterator();
72 while (iter.hasNext()) {
73 ObjectOutputStream cursorOOS = iter.next();
74 cursorOOS.writeObject(oMsg);
75 cursorOOS.flush();
76 }
77 }
78
79}