private void acceptConnection() throws IOException, BindException { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (!connected) { try { serverSocket = new ServerSocket(ipParameters.getPort()); LOG.debug("Start Accept on port: " + ipParameters.getPort()); socket = serverSocket.accept(); LOG.info("Connected: " + socket.getInetAddress() + ":" + ipParameters.getPort()); if (getePoll() != null) transport = new EpollStreamTransport( socket.getInputStream(), socket.getOutputStream(), getePoll()); else transport = new StreamTransport(socket.getInputStream(), socket.getOutputStream()); break; } catch (Exception e) { LOG.warn( "Open connection failed on port " + ipParameters.getPort() + ", caused by " + e.getLocalizedMessage(), e); if (e instanceof SocketTimeoutException) { continue; } else if (e.getLocalizedMessage().contains("closed")) { return; } else if (e instanceof BindException) { closeConnection(); throw (BindException) e; } } } } conn = getMessageControl(); conn.setExceptionHandler(getExceptionHandler()); conn.DEBUG = true; conn.start(transport, ipMessageParser, null, waitingRoomKeyFactory); if (getePoll() == null) ((StreamTransport) transport).start("Modbus4J TcpMaster"); connected = true; }
@Override public void run() { LOG.debug(" ListenerConnectionHandler::run() "); if (ipParameters.isEncapsulated()) { ipMessageParser = new EncapMessageParser(true); waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory(); } else { ipMessageParser = new XaMessageParser(true); waitingRoomKeyFactory = new XaWaitingRoomKeyFactory(); } try { acceptConnection(); } catch (IOException e) { LOG.debug("Error in TCP Listener! - " + e.getLocalizedMessage(), e); conn.close(); closeConnection(); getExceptionHandler().receivedException(new ModbusInitException(e)); } }