TD2: Fix all important bugs in the object passing server and client
[TD_SR.git] / TD2 / server / BroadcastThreadService.java
index 180f735b49fa442ed5982afa0a286d8c3f0ff879..cd971c252356d34b4821c6e170ec81aa462d6c46 100644 (file)
@@ -18,9 +18,7 @@ public class BroadcastThreadService implements Runnable {
        public void run() {
                try {
                        doService(clientSocket, listWriter);
-                       //FIXME: also close the BR and PW?
                        clientSocket.close();
-                       //FIXME: remove the associated PW from the ArrayList
                } catch (IOException e) {
                        System.err.println("IOException : " + e);
                        e.printStackTrace();
@@ -36,17 +34,31 @@ public class BroadcastThreadService implements Runnable {
                }
        }
 
+       /**
+        * Be careful, this function must be thread-safe
+        * @param  clientSocket [description]
+        * @param  sharedList   [description]
+        * @throws IOException  [description]
+        */
        public void doService(Socket clientSocket, ArrayList<PrintWriter> sharedList) throws IOException {
                BufferedReader in;
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
-               sharedList.add(new PrintWriter(clientSocket.getOutputStream()));
+               PrintWriter OWriter = new PrintWriter(clientSocket.getOutputStream());
+               sharedList.add(OWriter);
                boolean end = false;
                while (!end) {
                        String theLine = in.readLine();
-                       if (theLine.equals("."))
+                       if (theLine.equals(".")) {
                                end = true; // le thread de service doit terminer
+                               break; // do not broadcast the dot that will close all clients threads
+                       }
                        broadcastMsg(theLine);
                }
+               sharedList.remove(OWriter);
+               if (in != null)
+                       in.close();
+               if (OWriter != null)
+                       OWriter.close();
                System.out.println("Fin du thread repondant au client, port "
                                                        + clientSocket.getPort());
        }