List of usage examples for java.net Socket isConnected
public boolean isConnected()
From source file:org.archive.modules.fetcher.HeritrixProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the * given time limit./*ww w . j av a 2 s. com*/ * <p> * This method employs several techniques to circumvent the limitations * of older JREs that do not support connect timeout. When running in * JRE 1.4 or above reflection is used to call * Socket#connect(SocketAddress endpoint, int timeout) method. When * executing in older JREs a controller thread is executed. The * controller thread attempts to create a new socket within the given * limit of time. If socket constructor does not return until the * timeout expires, the controller terminates and throws an * {@link ConnectTimeoutException} * </p> * * @param host the host name/IP * @param port the port on the host * @param localAddress the local host name/IP to bind the socket to * @param localPort the port on the local machine * @param params {@link HttpConnectionParams Http connection parameters} * * @return Socket a new socket * * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * @throws IOException if an I/O error occurs while creating the socket * @throws UnknownHostException if the IP address of the host cannot be * determined * @throws ConnectTimeoutException if socket cannot be connected within the * given time limit * * @since 3.0 */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { socket = new Socket(); InetAddress hostAddress; Thread current = Thread.currentThread(); if (current instanceof HostResolver) { HostResolver resolver = (HostResolver) current; hostAddress = resolver.resolve(host); } else { hostAddress = null; } InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:com.cyberway.issue.crawler.fetcher.HeritrixSSLProtocolSocketFactory.java
public synchronized Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); }//from w w w .java 2 s. co m Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { SSLSocketFactory factory = (SSLSocketFactory) params.getParameter(FetchHTTP.SSL_FACTORY_KEY); SSLSocketFactory f = (factory != null) ? factory : this.sslDefaultFactory; socket = f.createSocket(); ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY); InetAddress hostAddress = (cache != null) ? HeritrixProtocolSocketFactory.getHostAddress(cache, host) : null; InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:org.bml.util.server.BServer.java
/** * The runInvProxy class starts a new server socket and listens for * connections from clients. Upon recieving a connection, it starts a new * InvProxyThread to process the connection. * @param aPort The port to attach to/*from ww w . j a v a 2 s . c o m*/ * @param aNumThreads the number of worker threads * @param aSleepTime sleep time in between checks * @param aMaxQueueLength the max requests to queue up * @param accessLog a Log to write access info */ public void runInvProxy(int aPort, int aNumThreads, long aSleepTime, int aMaxQueueLength, Log accessLog) { this.accessLog = accessLog; if (LOG.isDebugEnabled()) { LOG.debug("Attempting to start server on port: " + aPort); } //Start Server ServerSocket myServerSocket = null; try { myServerSocket = new ServerSocket(aPort, aMaxQueueLength); } catch (IOException e) { System.out.println(e); return; } if (LOG.isDebugEnabled()) { LOG.debug("Server started on port: " + aPort); } //Continuously accept connections and start threads to //process connections. while (!theDone) { if (LOG.isDebugEnabled()) { LOG.debug("Ready to accept client connection"); } Socket myClientSocket = null; try { myClientSocket = myServerSocket.accept(); } catch (IOException e) { System.out.println("Accept Error: " + e); break; } if (LOG.isDebugEnabled()) { LOG.debug("Accepted connection from client: " + myClientSocket.getInetAddress() + "\nStarting thread to deal with connection"); } //Make sure there aren't too many active threads if (aNumThreads != -1) { while (Thread.activeCount() > aNumThreads) { if (LOG.isDebugEnabled()) { LOG.debug("Too many active threads. Waiting " + aSleepTime + "(ms) before trying to start new HitServerInvProxyThread again"); } try { Thread.sleep(aSleepTime); } catch (InterruptedException e) { System.out.println(e); break; } } } if (myClientSocket != null && myClientSocket.isConnected()) { new InvProxyThread(this, myClientSocket, this.accessLog); } else { if (LOG.isWarnEnabled()) { LOG.warn("Client Socket is null or not connected when starting thread"); } break; } } //Closing socket if (LOG.isDebugEnabled()) { LOG.debug("Closing server socket. In general, we should never get here."); } try { myServerSocket.close(); } catch (IOException e) { System.out.println(e); return; } }
From source file:org.archive.modules.fetcher.HeritrixSSLProtocolSocketFactory.java
public synchronized Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException { // Below code is from the DefaultSSLProtocolSocketFactory#createSocket // method only it has workarounds to deal with pre-1.4 JVMs. I've // cut these out. if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); }// w w w . j ava 2s. co m Socket socket = null; int timeout = params.getConnectionTimeout(); if (timeout == 0) { socket = createSocket(host, port, localAddress, localPort); } else { SSLSocketFactory factory = (SSLSocketFactory) params.getParameter(FetchHTTP.SSL_FACTORY_KEY); SSLSocketFactory f = (factory != null) ? factory : this.sslDefaultFactory; socket = f.createSocket(); Thread current = Thread.currentThread(); InetAddress hostAddress; if (current instanceof HostResolver) { HostResolver resolver = (HostResolver) current; hostAddress = resolver.resolve(host); } else { hostAddress = null; } InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port) : new InetSocketAddress(host, port); socket.bind(new InetSocketAddress(localAddress, localPort)); try { socket.connect(address, timeout); } catch (SocketTimeoutException e) { // Add timeout info. to the exception. throw new SocketTimeoutException( e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms."); } assert socket.isConnected() : "Socket not connected " + host; } return socket; }
From source file:org.rifidi.emulator.io.comm.ip.tcpserver.TCPServerCommunicationIncomingConnectionHandler.java
/** * The main logic of this monitor, which creates a new server socket bound * to the current local IP / port combination and listens for clients to * connect until explictly unbound./* ww w . j a v a 2 s .c o m*/ * * @see java.lang.Runnable#run() */ public void run() { logger.debug("Attempting to create TCPServer..."); /* Create the ServerSocket and check to see * if the server socket was made successfully */ hasNoError = bindServerSocket(); if (hasNoError) { logger.debug("No error creating server, proceeding."); /* A string which will be used multiple times in log statements. */ String serverString = "[" + curServerSocket.getInetAddress().getHostAddress() + ":" + curServerSocket.getLocalPort() + "]"; /* Keep running while the server socket is open. */ while (!curServerSocket.isClosed() && hasNoError) { /* Try to accept a connection */ Socket curClientSocket = null; try { logger.debug(serverString + " - Waiting for client..."); curClientSocket = curServerSocket.accept(); curClientSocket.setKeepAlive(true); //TODO Maybe we should do a disconnect } catch (IOException e) { logger.debug(serverString + " - Server accept interrupted."); // Retry, because no Socket was created continue; } /* set the new Socket */ this.hostCommunication.setClientSocket(curClientSocket); /* Check to see if a client successfully connected */ if (curClientSocket != null) { final String connectionMessage = serverString + " - Client connected (" + curClientSocket.getInetAddress().getHostAddress() + ":" + curClientSocket.getPort() + ")"; /* Log the connection */ logger.info(connectionMessage); /* Call connect on the current communication. */ this.hostCommunication.connect(); /* Wait until the client socket is disconnected */ synchronized (curClientSocket) { while (!curClientSocket.isClosed() && curClientSocket.isConnected()) { try { /* Close the ServerSocket so that he couldn't accept * more than one connections a time (SYN/SYN ACK - Problem) */ curServerSocket.close(); /* wait until the client connection is closed */ curClientSocket.wait(); /* bind the ServerSocket again, so that * new Connections can be made */ PowerState powerState = this.hostCommunication.getPowerState(); logger.debug("Comm power state is " + powerState); if (powerState != TCPServerOffCommunicationPowerState.getInstance()) { hasNoError = bindServerSocket(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { logger.debug("Interrupted Exception happened."); } } /* Done waiting */ } } } /* while (!serverSocket.isClosed())... */ /* Server socket closed */ } else { /* Log the error message. */ logger.error(errorMessage); /* Force a shutdown of the component. */ this.hostCommunication.turnOff(); } /* All done running. */ }
From source file:net.emotivecloud.scheduler.drp4one.DRP4OVF.java
private boolean port22Reached(String ipAddress) { boolean gotPort22Connection = false; try {/* w ww . ja v a 2s . c o m*/ InetAddress toPoll = InetAddress.getByName(ipAddress); boolean reachable = false; try { // We have to answer within a WS timeout reachable = toPoll.isReachable(5000); } catch (IOException e) { // same as unreachable, log the problem if (log.isDebugEnabled()) { log.error(e); } else { log.error(e.getMessage()); } } if (reachable) { // see if we can ssh connect to port 22 try { Socket socket = new Socket(toPoll, 22); gotPort22Connection |= socket.isConnected(); socket.close(); } catch (IOException e) { // Happens when there's no one listening // on port 22, for example. Anyway, it // means we can't connect } } } catch (UnknownHostException e) { // Ignore, it's not a valid ip! } catch (SecurityException e) { if (log.isDebugEnabled()) { log.fatal(e); } else { log.fatal(e.getMessage()); } throw e; } return gotPort22Connection; }
From source file:com.symbian.driver.core.controller.tasks.TEFTask.java
/** * @param aVisitor//from w ww. j a v a 2 s . com * @param aTestExecuteScript * @param lExecuteOnDevice * @param aTask * @return The last execption raised when running UCC. * @throws JStatException */ private boolean runUCC(List<String> aArgs, Task aTask) { boolean lReturn = true; Socket lUccSocket = null; DataOutputStream lSocketOut = null; DataInputStream lSocketIn = null; int lRunNumber = 0; int lUccPort = -1; String lUccAddress = null; IDeviceComms.ISymbianProcess lProcess = null; try { String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":"); lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER); lUccAddress = lUccSplit[0]; lUccPort = Integer.parseInt(lUccSplit[1]); } catch (ParseException lParseException) { LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException); iExceptions.put(lParseException, ESeverity.ERROR); lReturn = false; } catch (NumberFormatException lNumberFormatException) { LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException); iExceptions.put(lNumberFormatException, ESeverity.ERROR); lReturn = false; } if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) { iExceptions.put( new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"), ESeverity.ERROR); return false; } // Run the test try { LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort); lUccSocket = new Socket(lUccAddress, lUccPort); lSocketOut = new DataOutputStream(lUccSocket.getOutputStream()); lSocketIn = new DataInputStream(lUccSocket.getInputStream()); LOGGER.fine("Starting UCC while still polling"); lProcess = iDeviceProxy.createSymbianProcess(); if (lProcess != null) { // run and don't wait if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) { iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR); lReturn = false; } // Tell UCC that the test has started. LOGGER.fine("Writing to UCC socket: " + lRunNumber); lSocketOut.writeInt(lRunNumber); lSocketOut.flush(); int lUCCReply = lSocketIn.readInt(); LOGGER.fine("UCC Reply: " + lUCCReply); } } catch (UnknownHostException lUnknownHostException) { LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException); iExceptions.put(lUnknownHostException, ESeverity.ERROR); return false; } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: " + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:" + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound() : "\nUcc Socket is NULL"), lIOException); iExceptions.put(lIOException, ESeverity.ERROR); return false; } finally { // Close UCC if (lSocketOut != null) { try { LOGGER.log(Level.FINE, "Closing Socket Out."); lUccSocket.shutdownInput(); lUccSocket.shutdownOutput(); lSocketOut.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (lSocketIn != null) { try { LOGGER.log(Level.FINE, "Closing Socket In."); lSocketIn.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (lUccSocket != null) { try { LOGGER.log(Level.FINE, "Closing Socket UCC."); lUccSocket.close(); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException); iExceptions.put(lIOException, ESeverity.ERROR); } } if (!lUccSocket.isClosed()) { LOGGER.warning("Could not close the UCC sockets properly."); } lSocketOut = null; lSocketIn = null; lUccSocket = null; // Poll TEF Test if (!lProcess.join()) { iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR); lReturn = false; } } return lReturn; }
From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java
public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException { final String methodName = IServiceCheckProcessor.CNAME + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException"; if (DEBUG) {/*from ww w . java2s. co m*/ DEBUGGER.debug(methodName); DEBUGGER.debug("ServiceCheckRequest: {}", request); } int exitCode = -1; Socket socket = null; File sourceFile = null; CommandLine command = null; BufferedWriter writer = null; ExecuteStreamHandler streamHandler = null; ByteArrayOutputStream outputStream = null; ServiceCheckResponse response = new ServiceCheckResponse(); final DefaultExecutor executor = new DefaultExecutor(); final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { switch (request.getRequestType()) { case NETSTAT: sourceFile = scriptConfig.getScripts().get("netstat"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; case REMOTEDATE: response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData(System.currentTimeMillis()); break; case TELNET: response = new ServiceCheckResponse(); int targetPort = request.getPortNumber(); String targetServer = request.getTargetHost(); if (DEBUG) { DEBUGGER.debug("Target port: {}", targetPort); DEBUGGER.debug("Target server: {}", targetServer); } if (targetPort == 0) { throw new ServiceCheckException("Target port number was not assigned. Cannot action request."); } final String CRLF = "\r\n"; final String TERMINATE_TELNET = "^]"; synchronized (new Object()) { InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort); socket = new Socket(); socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT); socket.setSoLinger(false, 0); socket.setKeepAlive(false); try { socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + targetServer + " on port " + request.getPortNumber()); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(TERMINATE_TELNET + CRLF); pWriter.flush(); pWriter.close(); response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " successful."); } catch (ConnectException cx) { response.setRequestStatus(AgentStatus.FAILURE); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " failed with message: " + cx.getMessage()); } } break; case PROCESSLIST: sourceFile = scriptConfig.getScripts().get("processList"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; default: // unknown operation throw new ServiceCheckException("No valid operation was specified"); } } catch (UnknownHostException uhx) { ERROR_RECORDER.error(uhx.getMessage(), uhx); throw new ServiceCheckException(uhx.getMessage(), uhx); } catch (SocketException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new ServiceCheckException(sx.getMessage(), sx); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new ServiceCheckException(iox.getMessage(), iox); } catch (InterruptedException ix) { ERROR_RECORDER.error(ix.getMessage(), ix); throw new ServiceCheckException(ix.getMessage(), ix); } finally { try { if (writer != null) { writer.close(); } if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } return response; }