df56d31ed4c87c18a7041241be3d870f258fde23
[TD_SR.git] / TD2 / server / BroadcastoThreadService.java
1 import java.net.*;
2 import java.io.*;
3 import java.util.*;
4
5 public 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 }
23 catch (IOException e) {
24 System.err.println("IOException : " + e);
25 e.printStackTrace();
26 }
27 catch (ClassNotFoundException e) {
28 System.err.println("ClassNotFoundException: " + e);
29 e.printStackTrace();
30 }
31 finally {
32 try {
33 if (this.clientSocket != null)
34 this.clientSocket.close();
35 }
36 catch (IOException e) {
37 System.err.println("IOException : " + e);
38 e.printStackTrace();
39 }
40 }
41 }
42
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 */
50 public void doService(Socket clientSocket, ArrayList<ObjectOutputStream> sharedList) throws IOException, ClassNotFoundException {
51 ObjectOutputStream OWriter = new ObjectOutputStream(clientSocket.getOutputStream());
52 ObjectInputStream OReader = new ObjectInputStream(clientSocket.getInputStream());
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 }
61 broadcastoMsg(roMsg);
62 }
63 sharedList.remove(OWriter);
64 if (OWriter != null)
65 OWriter.close();
66 if (OReader != null)
67 OReader.close();
68 System.out.println("Fin du thread repondant au client, port "
69 + clientSocket.getPort());
70 }
71
72 private void broadcastoMsg(Message oMsg) throws IOException, ClassNotFoundException {
73 ListIterator<ObjectOutputStream> iter = listoWriter.listIterator();
74 while (iter.hasNext()) {
75 ObjectOutputStream cursorOOS = iter.next();
76 cursorOOS.writeObject(oMsg);
77 cursorOOS.flush();
78 }
79 }
80
81 }