| 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 | } 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 | |
| 41 | public void doService(Socket clientSocket, ArrayList<ObjectOutputStream> sharedList) throws IOException, ClassNotFoundException { |
| 42 | ObjectInputStream OReader = new ObjectInputStream(clientSocket.getInputStream()); |
| 43 | ObjectOutputStream OWriter = new ObjectOutputStream(clientSocket.getOutputStream()); |
| 44 | sharedList.add(OWriter); |
| 45 | boolean end = false; |
| 46 | while (!end) { |
| 47 | Message roMsg = (Message)OReader.readObject(); |
| 48 | if (roMsg.getTexte().equals(".")) { |
| 49 | end = true; // le thread de service doit terminer |
| 50 | break; // do not broadcast the dot that will close all clients threads |
| 51 | } |
| 52 | broadcastoMsg(roMsg); |
| 53 | } |
| 54 | sharedList.remove(OWriter); |
| 55 | if (OReader != null) |
| 56 | OReader.close(); |
| 57 | if (OWriter != null) |
| 58 | OWriter.close(); |
| 59 | System.out.println("Fin du thread repondant au client, port " |
| 60 | + clientSocket.getPort()); |
| 61 | } |
| 62 | |
| 63 | private void broadcastoMsg(Message oMsg) throws IOException, ClassNotFoundException { |
| 64 | ListIterator<ObjectOutputStream> iter = listoWriter.listIterator(); |
| 65 | while (iter.hasNext()) { |
| 66 | ObjectOutputStream cursorOOS = iter.next(); |
| 67 | cursorOOS.writeObject(oMsg); |
| 68 | cursorOOS.flush(); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | } |