/** Begin running the websocket server. */ @Override public void run() { try { Logger.info( MessageFormat.format("WebSocketServerBridge listening on port {0}...", this.port)); serverSocket = new ServerSocket(this.port); // Waiting for the server socket to close or until the server is shutdown manually. while ((this.isServerRunning) && (!serverSocket.isClosed())) { // Wait for incoming connections. Socket socket = serverSocket.accept(); // Try to reclaim any threads if we are exceeding our maximum. // TimeComplexity: O(n) -- Where n is the number of threads valid or invalid. // NOTE: Minimal unit testing has been done here...more testing is required. if (threads.size() + 1 > this.getMaximumThreads()) { for (int i = 0; i < threads.size(); i++) { if (!threads.get(i).isAlive()) { threads.remove(i); } } } // Make sure we have enough threads before accepting. // NOTE: Minimal unit testing has been done here...more testing is required. if ((threads.size() + 1) <= this.getMaximumThreads()) { Connection t = new Connection(socket, this.serviceLayer, this); t.start(); threads.add(t); } else { Logger.debug("The server has reached its thread maximum..."); } } // END OF while ( (this.isServerRunning) && (!serverSocket.isClosed()) )... Logger.info("WebSocket server stopping..."); } catch (IOException ioException) { // --- CR (8/10/13) --- Only log the event if the server is still running. This should // prevent an error message from appearing when the server is restarted. if (this.isServerRunning) { Logger.info( MessageFormat.format("The port {0} could not be opened for WebSockets.", this.port)); Logger.debug(ioException.getMessage()); } // Close all threads. // TimeComplexity: O(n) -- Where n is the number of threads valid or invalid. for (Connection t : threads) { if (t.isAlive()) { t.close(); } } } }