/** * Creates a socket server on the given port. The socket server receives and responds to agent requests using the * request handler. * * @param requestHandler * - the {@link RequestHandler} instance that will be used for request handling * @param port * - port on which to open a socket server * @throws IOException * - if the input or output stream initialization fails */ public SocketConnectionHandler(RequestHandler<T> requestHandler, int port) throws IOException { socketServer = new DeviceSocketServer<T>(requestHandler, port); isRunning = false; }
/** * Terminates the work of the socket server. * * @throws IOException * - if closing the input or output streams fails */ public void terminateSocketServer() throws IOException { socketServer.stop(); } }
@Override public void run() { isRunning = true; while (isRunning) { try { LOGGER.info("Waiting for connection..."); socketServer.acceptConnection(); LOGGER.info("Connection accepted, receiving request..."); Request<T> request = socketServer.handle(); LOGGER.info("Handled request '" + request.getType() + "'."); } catch (SocketException se) { LOGGER.error("Error in connection.", se); } catch (IOException ioe) { LOGGER.error("Error in I/O.", ioe); } catch (ClassNotFoundException e) { LOGGER.error("Unsupported request sent.", e); } // Closing the connection in a separate block try { socketServer.endConnection(); LOGGER.info("Connection closed."); } catch (IOException e) { LOGGER.error("Error in I/O while closing connection.", e); } } }
/** * Handles the next request sent by the client using the {@link RequestHandler} that was specified when this class * was created. * * @return the {@link Request} that was handled. * @throws IOException * if an I/O exception of some sort has occurred. * @throws ClassNotFoundException * thrown when an application fails to load in a class. */ @SuppressWarnings("unchecked") public Request<T> handle() throws IOException, ClassNotFoundException { Request<T> request = (Request<T>) receiveObject(); Object response = requestHandler.handle(request); sendObject(response); return request; } }