List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { Args.notNull(host, "HTTP host"); Args.notNull(remoteAddress, "Remote address"); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress);// w w w . j a v a2 s . c om } try { if (connectTimeout > 0 && sock.getSoTimeout() == 0) { sock.setSoTimeout(connectTimeout); } if (this.log.isDebugEnabled()) { this.log.debug("Connecting socket to " + remoteAddress + " with timeout " + connectTimeout); } sock.connect(remoteAddress, connectTimeout); } catch (final IOException ex) { try { sock.close(); } catch (final IOException ignore) { } throw ex; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; this.log.debug("Starting handshake"); sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates an telnet connection to a target host and port number. Silently * succeeds if no issues are encountered, if so, exceptions are logged and * re-thrown back to the requestor.//from ww w. j a v a 2s. c o m * * If an exception is thrown during the <code>socket.close()</code> operation, * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate * a connection failure (indeed, it means the connection succeeded) but it is * logged because continued failures to close the socket could result in target * system instability. * * @param hostName - The target host to make the connection to * @param portNumber - The port number to attempt the connection on * @param timeout - How long to wait for a connection to establish or a response from the target * @param object - The serializable object to send to the target * @return <code>Object</code> as output from the request * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug(hostName); DEBUGGER.debug("portNumber: {}", portNumber); DEBUGGER.debug("timeout: {}", timeout); DEBUGGER.debug("object: {}", object); } Socket socket = null; Object resObject = null; try { synchronized (new Object()) { if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) { throw new UnknownHostException("No host was found in DNS for the given name: " + hostName); } InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber); socket = new Socket(); socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout)); socket.setSoLinger(false, 0); socket.setKeepAlive(false); socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout)); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber); } ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream()); if (DEBUG) { DEBUGGER.debug("ObjectOutputStream: {}", objectOut); } objectOut.writeObject(object); resObject = new ObjectInputStream(socket.getInputStream()).readObject(); if (DEBUG) { DEBUGGER.debug("resObject: {}", resObject); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF); pWriter.flush(); pWriter.close(); } } catch (ConnectException cx) { throw new UtilityException(cx.getMessage(), cx); } catch (UnknownHostException ux) { throw new UtilityException(ux.getMessage(), ux); } catch (SocketException sx) { throw new UtilityException(sx.getMessage(), sx); } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } catch (ClassNotFoundException cnfx) { throw new UtilityException(cnfx.getMessage(), cnfx); } finally { try { if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { // log it - this could cause problems later on ERROR_RECORDER.error(iox.getMessage(), iox); } } return resObject; }
From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java
/** * Connect via socket./* ww w . j a v a2s. c o m*/ * @param connectTimeout the timeout * @param socket the socket * @param host the host * @param remoteAddress the remote address * @param localAddress the local address * @param context the context * @return the created/connected socket * @throws IOException in case of problems */ @Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { final HttpHost socksProxy = SocksConnectionSocketFactory.getSocksProxy(context); if (socksProxy != null) { final Socket underlying = SocksConnectionSocketFactory.createSocketWithSocksProxy(socksProxy); underlying.setReuseAddress(true); // TODO: commented out for HttpClient 4.3 // final int soTimeout = HttpConnectionParams.getSoTimeout(params); final SocketAddress socksProxyAddress = new InetSocketAddress(socksProxy.getHostName(), socksProxy.getPort()); try { //underlying.setSoTimeout(soTimeout); underlying.connect(remoteAddress, connectTimeout); } catch (final SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + socksProxyAddress + " timed out"); } final Socket sslSocket = getSSLSocketFactory().createSocket(underlying, socksProxy.getHostName(), socksProxy.getPort(), true); configureSocket((SSLSocket) sslSocket, context); return sslSocket; } try { return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context); } catch (final IOException e) { if (useInsecureSSL_ && "handshake alert: unrecognized_name".equals(e.getMessage())) { setEmptyHostname(host); return super.connectSocket(connectTimeout, createSocket(context), host, remoteAddress, localAddress, context); } throw e; } }
From source file:org.glite.security.trustmanager.axis2.AXIS2SocketFactory.java
/** * Connect socket to remote host.// ww w .j av a2 s . c o m * * @param socket the socket to be connected * @param remoteaddr remote host and port * @param localaddr optional local host and port * @param timeout optional timeout, default if used if timeout == 0 * * @return original socket **/ private final Socket connectSocket(Socket socket, SocketAddress remoteaddr, SocketAddress localaddr, int timeout) throws IOException { int newTimeout = timeout; if (localaddr != null) { socket.bind(localaddr); } // if no timeout is given, see if the property is set and use that if (timeout == 0) { String timeoutString = getCurrentProperties().getProperty(ContextWrapper.SSL_TIMEOUT_SETTING, ContextWrapper.TIMEOUT_DEFAULT); newTimeout = Integer.parseInt(timeoutString); } socket.setSoTimeout(newTimeout); socket.connect(remoteaddr, newTimeout); return socket; }
From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the given time limit. * <p>//from w w w . j av a 2s .c om * 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 determined */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); Socket socket = null; SocketFactory socketfactory = SSLSocketFactory.getDefault(); if (timeout == 0) { socket = socketfactory.createSocket(host, port, localAddress, localPort); } else { socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); } verifyHostname((SSLSocket) socket); return socket; }
From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the given time limit. * <p>/*from w w w. ja v a 2 s . c o m*/ * To circumvent the limitations of older JREs that do not support connect timeout 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 * determined */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); Socket socket = null; SocketFactory socketfactory = getSSLContext().getSocketFactory(); if (timeout == 0) { socket = socketfactory.createSocket(host, port, localAddress, localPort); } else { socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); } verifyHostname((SSLSocket) socket); return socket; }
From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java
/** * Attempts to get a new socket connection to the given host within the * given time limit.// w w w . j a v a 2 s. c o m * <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 clientHost * the local host name/IP to bind the socket to * @param clientPort * 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 determined */ public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); Socket socket = null; SocketFactory socketfactory = getSslSocketFactory(); if (timeout == 0) { socket = socketfactory.createSocket(host, port, localAddress, localPort); } else { socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); } verifyHostname((SSLSocket) socket); return socket; }
From source file:com.meidusa.venus.io.network.VenusBIOConnectionFactory.java
public VenusBIOConnection makeObject() throws Exception { Socket socket = new Socket(); InetSocketAddress address = null; if (host == null) { address = new InetSocketAddress(port); } else {/*from w w w . j a v a 2 s. c om*/ address = new InetSocketAddress(host, port); } socket.setSendBufferSize(sendBufferSize * 1024); socket.setReceiveBufferSize(receiveBufferSize * 1024); socket.setTcpNoDelay(tcpNoDelay); socket.setKeepAlive(keepAlive); try { if (soTimeout > 0) { socket.setSoTimeout(soTimeout); } if (coTimeout > 0) { socket.connect(address, coTimeout); } else { socket.connect(address); } } catch (ConnectException e) { throw new ConnectException(e.getMessage() + " " + address.getHostName() + ":" + address.getPort()); } VenusBIOConnection conn = new VenusBIOConnection(socket, TimeUtil.currentTimeMillis()); byte[] bts = conn.read(); HandshakePacket handshakePacket = new HandshakePacket(); handshakePacket.init(bts); AuthenPacket authen = getAuthenticator().createAuthenPacket(handshakePacket); conn.write(authen.toByteArray()); bts = conn.read(); int type = AbstractServicePacket.getType(bts); if (type == PacketConstant.PACKET_TYPE_OK) { if (authenticatorLogger.isInfoEnabled()) { authenticatorLogger.info("authenticated by server=" + host + ":" + port + " success"); } } else if (type == PacketConstant.PACKET_TYPE_ERROR) { ErrorPacket error = new ErrorPacket(); error.init(bts); if (authenticatorLogger.isInfoEnabled()) { authenticatorLogger.info("authenticated by server=" + host + ":" + port + " error={code=" + error.errorCode + ",message=" + error.message + "}"); } throw new AuthenticationException(error.message, error.errorCode); } return conn; }
From source file:org.sonatype.nexus.internal.httpclient.NexusSSLConnectionSocketFactory.java
@Override @IgnoreJRERequirement//from ww w .j a v a2 s . c o m public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { checkNotNull(host); checkNotNull(remoteAddress); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress); } // NEXUS-6838: Server Name Indication support, a TLS feature that allows SSL // "virtual hosting" (multiple certificates) over single IP address + port. // Some CDN solutions requires this for HTTPS, as they choose certificate // to use based on "expected" hostname that is being passed here below // and is used during SSL handshake. Requires Java7+ if (sock instanceof SSLSocketImpl) { ((SSLSocketImpl) sock).setHost(host.getHostName()); } try { sock.connect(remoteAddress, connectTimeout); } catch (final IOException e) { Closeables.close(sock, true); throw e; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }