List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
From source file:com.hijacker.MainActivity.java
static Socket connect() { //Can be called from any thread, blocks until the job is finished Socket socket; try {//from w w w . java 2s . c o m InetAddress ip = Inet4Address.getByName(SERVER); socket = new Socket(); socket.connect(new InetSocketAddress(ip, PORT), 2000); PrintWriter in = new PrintWriter(socket.getOutputStream()); BufferedReader out = new BufferedReader(new InputStreamReader(socket.getInputStream())); //Authenticate (receive a string generated by the server, combine it with a stored key and send back the hashcode) if (debug) Log.d("HIJACKER/connect", "Authenticating with server..."); String temp = out.readLine() + AUTH_KEY; in.print(Integer.toString(temp.hashCode()) + '\n'); in.flush(); temp = out.readLine(); if (temp != null) { if (!temp.equals(ANS_POSITIVE)) return null; //Not authenticated, socket will be closed by the server } else return null; //Connection closed, probably not authenticated if (debug) Log.d("HIJACKER/connect", "Authenticated"); if (deviceID == -1) { if (debug) Log.d("HIJACKER/connect", "Getting new deviceID..."); in.print(REQ_NEW_ID + '\n'); in.flush(); try { deviceID = Long.parseLong(out.readLine()); if (pref_edit != null) { pref_edit.putLong("deviceID", deviceID); pref_edit.commit(); } if (debug) Log.d("HIJACKER/connect", "New deviceID is " + deviceID); } catch (NumberFormatException ignored) { if (debug) Log.d("HIJACKER/connect", "deviceID caused NumberFormatException, still -1"); } } //String should be: info APP_VERSION_NAME APP_VERSION_CODE ANDROID_VERSION DEVICE_MODEL DEVICE_ID in.print(REQ_INFO + " " + versionName + " " + versionCode + " " + Build.VERSION.SDK_INT + " " + deviceModel + " " + deviceID + '\n'); in.flush(); } catch (IOException e) { Log.e("HIJACKER/connect", e.toString()); return null; } return socket; }
From source file:org.darkphoenixs.pool.socket.SocketConnectionFactory.java
@Override public Socket createConnection() throws Exception { Socket socket = new Socket(); try {/* w w w. ja v a2 s. com*/ if (sendBufferSize > 0) socket.setSendBufferSize(sendBufferSize); if (receiveBufferSize > 0) socket.setReceiveBufferSize(receiveBufferSize); if (soTimeout > 0) socket.setSoTimeout(soTimeout); if (linger > 0) socket.setSoLinger(true, linger); if (keepAlive) socket.setKeepAlive(keepAlive); if (tcpNoDelay) socket.setTcpNoDelay(tcpNoDelay); if (performance != null) socket.setPerformancePreferences(Integer.parseInt(performance[0]), Integer.parseInt(performance[1]), Integer.parseInt(performance[2])); socket.connect(socketAddress, connectionTimeout); } catch (Exception se) { socket.close(); throw se; } return socket; }
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./*from ww w .java2 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 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:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.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);/*from w w w .j a va2s . co m*/ } 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:org.apache.slider.common.tools.SliderUtils.java
@SuppressWarnings("SocketOpenedButNotSafelyClosed") public static void checkPort(String name, InetSocketAddress address, int connectTimeout) throws IOException { Socket socket = null; try {/* w ww. ja v a 2 s. com*/ socket = new Socket(); socket.connect(address, connectTimeout); } catch (Exception e) { throw new IOException("Failed to connect to " + name + " at " + address + " after " + connectTimeout + "millisconds" + ": " + e, e); } finally { IOUtils.closeSocket(socket); } }
From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientProtocolSocketFactory.java
public Socket connectSocket(final Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int timeout = params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0); Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, ECFHttpClientProtocolSocketFactory.class, "connectSocket " + remoteAddress.toString() + " timeout=" + timeout); //$NON-NLS-1$ //$NON-NLS-2$ try {//from ww w . j a va2 s . c o m // Use String.valueOf to protect against null Trace.trace(Activator.PLUGIN_ID, "bind(" + String.valueOf(localAddress) + ")"); //$NON-NLS-1$//$NON-NLS-2$ sock.bind(localAddress); Trace.trace(Activator.PLUGIN_ID, "connect(" + remoteAddress.toString() + ", " + timeout + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ sock.connect(remoteAddress, timeout); Trace.trace(Activator.PLUGIN_ID, "connected"); //$NON-NLS-1$ } catch (IOException e) { Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, ECFHttpClientProtocolSocketFactory.class, "createSocket", e); //$NON-NLS-1$ fireEvent(socketConnectListener, new SocketClosedEvent(source, sock, sock)); Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, ECFHttpClientProtocolSocketFactory.class, "createSocket", e); //$NON-NLS-1$ throw e; } Socket toReturn; Socket wrapped = new CloseMonitoringSocket(sock, socketConnectListener, source); SocketConnectedEvent connectedEvent = new SocketConnectedEvent(source, sock, wrapped); fireEvent(socketConnectListener, connectedEvent); // Change the wrapped socket if one of the receivers of the SocketConnectedEvent changed it if (connectedEvent.getSocket() != wrapped) { toReturn = connectedEvent.getSocket(); ((CloseMonitoringSocket) wrapped).setWrappedSocket(toReturn); } else { toReturn = wrapped; } return toReturn; }
From source file:com.raddle.tools.ClipboardTransferMain.java
private Object doInSocket(SocketCallback callback) { Socket socket = null; try {// w ww . j a va 2 s . co m String address = serverAddrTxt.getText(); String[] ipport = address.split(":"); if (ipport.length != 2) { updateMessage("????"); return null; } socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(ipport[0], Integer.parseInt(ipport[1])); socket.connect(socketAddress, 2000); socket.setSoTimeout(10000); return callback.connected(socket); } catch (Exception e) { e.printStackTrace(); updateMessage("?" + e.getMessage()); return null; } finally { if (socket != null) { try { socket.getInputStream().close(); } catch (IOException e) { } try { socket.getOutputStream().close(); } catch (IOException e) { } try { socket.close(); } catch (IOException e) { } } } }
From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java
/** * Default public constructor.//from w w w. j a v a2 s. c om * * @param http * @param url * @param knownMetadata * @throws IOException * @throws HttpException */ public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException { this.http = http; this.url = url; Scheme scheme = null; if ("http".equals(url.getProtocol())) { scheme = Scheme.HTTP; } else if ("https".equals(url.getProtocol())) { scheme = Scheme.HTTPS; } else { throw new IOException("Unknown scheme (not http/https) for url:" + url); } String path = "".equals(url.getFile()) ? "/" : url.getFile(); // some servers will redirect a request with a host line like // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they // don't want the :80... String host = url.getHost(); int port; String portString; if (url.getPort() == -1) { if (scheme == Scheme.HTTP) { port = 80; } else { port = 443; } portString = ""; } else { port = url.getPort(); portString = ":" + port; } Socket socket = null; try { socket = new Socket(); // create the socket socket.setSoTimeout(http.getTimeout()); // connect String sockHost = http.useProxy() ? http.getProxyHost() : host; int sockPort = http.useProxy() ? http.getProxyPort() : port; InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort); socket.connect(sockAddr, http.getTimeout()); if (scheme == Scheme.HTTPS) { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true); sslsocket.setUseClientMode(true); // Get the protocols and ciphers supported by this JVM Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols())); Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites())); // Intersect with preferred protocols and ciphers protocols.retainAll(http.getTlsPreferredProtocols()); ciphers.retainAll(http.getTlsPreferredCipherSuites()); sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()])); sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); sslsocket.startHandshake(); socket = sslsocket; } this.conf = http.getConf(); if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) { headers.setValue("_ip_", sockAddr.getAddress().getHostAddress()); } // make request OutputStream req = socket.getOutputStream(); StringBuffer reqStr = new StringBuffer("GET "); if (http.useProxy()) { reqStr.append(url.getProtocol() + "://" + host + portString + path); } else { reqStr.append(path); } reqStr.append(" HTTP/1.0\r\n"); reqStr.append("Host: "); reqStr.append(host); reqStr.append(portString); reqStr.append("\r\n"); reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n"); String userAgent = http.getUserAgent(); if ((userAgent == null) || (userAgent.length() == 0)) { if (HttpProtocol.LOGGER.isErrorEnabled()) { HttpProtocol.LOGGER.error("User-agent is not set!"); } } else { reqStr.append("User-Agent: "); reqStr.append(userAgent); reqStr.append("\r\n"); } reqStr.append("Accept-Language: "); reqStr.append(this.http.getAcceptLanguage()); reqStr.append("\r\n"); reqStr.append("Accept: "); reqStr.append(this.http.getAccept()); reqStr.append("\r\n"); if (knownMetadata != null) { String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified"); if (StringUtils.isNotBlank(ifModifiedSince)) { reqStr.append("If-Modified-Since: "); reqStr.append(ifModifiedSince); reqStr.append("\r\n"); } String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag"); if (StringUtils.isNotBlank(ifNoneMatch)) { reqStr.append("If-None-Match: "); reqStr.append(ifNoneMatch); reqStr.append("\r\n"); } } reqStr.append("\r\n"); // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default // charset // TODO use UTF-8 and set a charset value explicitely byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1); req.write(reqBytes); req.flush(); PushbackInputStream in = // process response new PushbackInputStream( new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE), HttpProtocol.BUFFER_SIZE); StringBuffer line = new StringBuffer(); boolean haveSeenNonContinueStatus = false; while (!haveSeenNonContinueStatus) { // parse status code line this.code = parseStatusLine(in, line); // parse headers parseHeaders(in, line); haveSeenNonContinueStatus = code != 100; // 100 is // "Continue" } String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING); if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) { readChunkedContent(in, line); } else { readPlainContent(in); } String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING); if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { content = http.processGzipEncoded(content, url); } else if ("deflate".equals(contentEncoding)) { content = http.processDeflateEncoded(content, url); } else { HttpProtocol.LOGGER.trace("fetched {} bytes from {}", content.length, url); } } finally { if (socket != null) socket.close(); } }
From source file:ro.ui.pttdroid.Main.java
private synchronized void test_socket_server() { Log.i(SOCKET_TAG_STRING, "Testing server connection"); new Thread() { @Override//from w ww . j ava 2 s .co m public void run() { Socket client = new Socket(); InetSocketAddress isa = new InetSocketAddress("192.168.49.1", 8888); try { client.connect(isa, 10000); Log.i(SOCKET_TAG_STRING, "Connected!!"); BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream()); out.write("Send From Client ".getBytes()); out.flush(); out.close(); out = null; client.close(); client = null; EventBus.getDefault().post(new NewServerConnectionEvent("192.168.49.1")); } catch (Exception e) { Log.i(SOCKET_TAG_STRING, "error!!!"); Log.i(SOCKET_TAG_STRING, e.toString()); } } }.start(); }
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"); }/*w w w . j a v a 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; }