List of usage examples for java.net Socket connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
From source file:org.apache.jxtadoop.net.NetUtils.java
/** * This is a drop-in replacement for //from w w w . j a va 2s .c o m * {@link Socket#connect(SocketAddress, int)}. * In the case of normal sockets that don't have associated channels, this * just invokes <code>socket.connect(endpoint, timeout)</code>. If * <code>socket.getChannel()</code> returns a non-null channel, * connect is implemented using Hadoop's selectors. This is done mainly * to avoid Sun's connect implementation from creating thread-local * selectors, since Hadoop does not have control on when these are closed * and could end up taking all the available file descriptors. * * @see java.net.Socket#connect(java.net.SocketAddress, int) * * @param socket * @param endpoint * @param timeout - timeout in milliseconds */ public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (ch == null) { // let the default implementation handle it. socket.connect(endpoint, timeout); } else { SocketIOWithTimeout.connect(ch, endpoint, timeout); } }
From source file:net.NetUtils.java
/** * This is a drop-in replacement for //from w ww .j av a 2 s . c o m * {@link Socket#connect(SocketAddress, int)}. * In the case of normal sockets that don't have associated channels, this * just invokes <code>socket.connect(endpoint, timeout)</code>. If * <code>socket.getChannel()</code> returns a non-null channel, * connect is implemented using Hadoop's selectors. This is done mainly * to avoid Sun's connect implementation from creating thread-local * selectors, since Hadoop does not have control on when these are closed * and could end up taking all the available file descriptors. * * @see java.net.Socket#connect(java.net.SocketAddress, int) * * @param socket * @param endpoint * @param timeout - timeout in milliseconds */ public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (ch == null) { // let the default implementation handle it. socket.connect(endpoint, timeout); } else { SocketIOWithTimeout.connect(ch, endpoint, timeout); } // There is a very rare case allowed by the TCP specification, such that // if we are trying to connect to an endpoint on the local machine, // and we end up choosing an ephemeral port equal to the destination port, // we will actually end up getting connected to ourself (ie any data we // send just comes right back). This is only possible if the target // daemon is down, so we'll treat it like connection refused. if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) { LOG.info("Detected a loopback TCP socket, disconnecting it"); socket.close(); throw new ConnectException("Localhost targeted connection resulted in a loopback. " + "No daemon is listening on the target port."); } }
From source file:org.apache.hadoop.hdfs.server.namenode.TestAccessTokenWithDFS.java
private static void tryRead(Configuration conf, LocatedBlock lblock, boolean shouldSucceed) { InetSocketAddress targetAddr = null; Socket s = null; BlockReader blockReader = null;/*from ww w.j a v a 2 s . co m*/ Block block = lblock.getBlock(); try { DatanodeInfo[] nodes = lblock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getName()); s = new Socket(); s.connect(targetAddr, HdfsConstants.READ_TIMEOUT); s.setSoTimeout(HdfsConstants.READ_TIMEOUT); blockReader = BlockReader.newBlockReader(s, targetAddr.toString() + ":" + block.getBlockId(), block.getBlockId(), lblock.getAccessToken(), block.getGenerationStamp(), 0, -1, conf.getInt("io.file.buffer.size", 4096)); } catch (IOException ex) { if (ex instanceof InvalidAccessTokenException) { assertFalse("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid", shouldSucceed); return; } fail("OP_READ_BLOCK failed due to reasons other than access token"); } finally { if (s != null) { try { s.close(); } catch (IOException iex) { } finally { s = null; } } } if (blockReader == null) { fail("OP_READ_BLOCK failed due to reasons other than access token"); } assertTrue("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", shouldSucceed); }
From source file:org.apache.hadoop.hdfs.server.namenode.TestBlockTokenWithDFS.java
private static void tryRead(Configuration conf, LocatedBlock lblock, boolean shouldSucceed) { InetSocketAddress targetAddr = null; Socket s = null; DFSClient.BlockReader blockReader = null; Block block = lblock.getBlock();/*from www. jav a 2 s .c om*/ try { DatanodeInfo[] nodes = lblock.getLocations(); targetAddr = NetUtils.createSocketAddr(nodes[0].getName()); s = new Socket(); s.connect(targetAddr, HdfsConstants.READ_TIMEOUT); s.setSoTimeout(HdfsConstants.READ_TIMEOUT); blockReader = DFSClient.BlockReader.newBlockReader(s, targetAddr.toString() + ":" + block.getBlockId(), block.getBlockId(), lblock.getBlockToken(), block.getGenerationStamp(), 0, -1, conf.getInt("io.file.buffer.size", 4096)); } catch (IOException ex) { if (ex instanceof InvalidBlockTokenException) { assertFalse("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid", shouldSucceed); return; } fail("OP_READ_BLOCK failed due to reasons other than access token"); } finally { if (s != null) { try { s.close(); } catch (IOException iex) { } finally { s = null; } } } if (blockReader == null) { fail("OP_READ_BLOCK failed due to reasons other than access token"); } assertTrue("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid", shouldSucceed); }
From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java
public static void stop(final Log LOG, final ProcessDescription cfg) throws Exception { boolean isNew = false; if (cfg.getProcess() != null || isNew) { LOG.info("Stopping Launchpad " + cfg.getId()); boolean destroy = true; final int twoMinutes = 2 * 60 * 1000; final File controlPortFile = getControlPortFile(cfg.getDirectory()); LOG.debug("Control port file " + controlPortFile + " exists: " + controlPortFile.exists()); if (controlPortFile.exists()) { // reading control port int controlPort = -1; String secretKey = null; LineNumberReader lnr = null; String serverName = null; try { lnr = new LineNumberReader(new FileReader(controlPortFile)); final String portLine = lnr.readLine(); final int pos = portLine.indexOf(':'); controlPort = Integer.parseInt(portLine.substring(pos + 1)); if (pos > 0) { serverName = portLine.substring(0, pos); }//w w w . j a v a 2 s .c om secretKey = lnr.readLine(); } catch (final NumberFormatException ignore) { // we ignore this LOG.debug("Error reading control port file " + controlPortFile, ignore); } catch (final IOException ignore) { // we ignore this LOG.debug("Error reading control port file " + controlPortFile, ignore); } finally { IOUtils.closeQuietly(lnr); } if (controlPort != -1) { final List<String> hosts = new ArrayList<String>(); if (serverName != null) { hosts.add(serverName); } hosts.add("localhost"); hosts.add("127.0.0.1"); LOG.debug("Found control port " + controlPort); int index = 0; while (destroy && index < hosts.size()) { final String hostName = hosts.get(index); Socket clientSocket = null; DataOutputStream out = null; BufferedReader in = null; try { LOG.debug("Trying to connect to " + hostName + ":" + controlPort); clientSocket = new Socket(); // set a socket timeout clientSocket.connect(new InetSocketAddress(hostName, controlPort), twoMinutes); // without that, read() call on the InputStream associated with this Socket is infinite clientSocket.setSoTimeout(twoMinutes); LOG.debug(hostName + ":" + controlPort + " connection estabilished, sending the 'stop' command..."); out = new DataOutputStream(clientSocket.getOutputStream()); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); if (secretKey != null) { out.writeBytes(secretKey); out.write(' '); } out.writeBytes("stop\n"); in.readLine(); destroy = false; LOG.debug("'stop' command sent to " + hostName + ":" + controlPort); } catch (final Throwable ignore) { // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions // we ignore this for now LOG.debug("Error sending 'stop' command to " + hostName + ":" + controlPort + " due to: " + ignore.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(clientSocket); } index++; } } } if (cfg.getProcess() != null) { final Process process = cfg.getProcess(); if (!destroy) { // as shutdown might block forever, we use a timeout final long now = System.currentTimeMillis(); final long end = now + twoMinutes; LOG.debug("Waiting for process to stop..."); while (isAlive(process) && (System.currentTimeMillis() < end)) { try { Thread.sleep(2500); } catch (InterruptedException e) { // ignore } } if (isAlive(process)) { LOG.debug("Process timeout out after 2 minutes"); destroy = true; } else { LOG.debug("Process stopped"); } } if (destroy) { LOG.debug("Destroying process..."); process.destroy(); LOG.debug("Process destroyed"); } cfg.setProcess(null); } } else { LOG.warn("Launchpad already stopped"); } }
From source file:org.apache.hama.util.BSPNetUtils.java
/** * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a * local address and port to bind the socket to. * //from w w w . ja v a 2s .co m * @param socket * @param endpoint the remote address * @param localAddr the local address to bind the socket to * @param timeout timeout in milliseconds */ public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout) throws IOException { if (socket == null || endpoint == null || timeout < 0) { throw new IllegalArgumentException("Illegal argument for connect()"); } SocketChannel ch = socket.getChannel(); if (localAddr != null) { socket.bind(localAddr); } if (ch == null) { // let the default implementation handle it. socket.connect(endpoint, timeout); } else { SocketIOWithTimeout.connect(ch, endpoint, timeout); } // There is a very rare case allowed by the TCP specification, such that // if we are trying to connect to an endpoint on the local machine, // and we end up choosing an ephemeral port equal to the destination port, // we will actually end up getting connected to ourself (ie any data we // send just comes right back). This is only possible if the target // daemon is down, so we'll treat it like connection refused. if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) { LOG.info("Detected a loopback TCP socket, disconnecting it"); socket.close(); throw new ConnectException("Localhost targeted connection resulted in a loopback. " + "No daemon is listening on the target port."); } }
From source file:org.mycard.net.network.HttpConnection.java
/*** * Opens the connection to a http server * * @return the opened low level connection * @throws IOException if the connection fails for any reason. */// w ww . ja v a 2 s.c o m @Override AndroidHttpClientConnection openConnection(Request req) throws IOException { // Update the certificate info (connection not secure - set to null) //EventHandler eventHandler = req.getEventHandler(); //mCertificate = null; //eventHandler.certificate(mCertificate); AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); BasicHttpParams params = new BasicHttpParams(); Socket sock = new Socket(); sock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort()), 20 * 1000); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); conn.bind(sock, params); return conn; }
From source file:com.googlecode.jsendnsca.NagiosPassiveCheckSender.java
private Socket connectedToNagios() throws IOException { Socket socket = new Socket(); socket.connect(new InetSocketAddress(nagiosSettings.getNagiosHost(), nagiosSettings.getPort()), nagiosSettings.getConnectTimeout()); socket.setSoTimeout(nagiosSettings.getTimeout()); return socket; }
From source file:nfinity.FindPeer.java
public Boolean ConnectPeerListener(String ip) { try {//from w w w. ja v a 2 s.co m //Soocket = socket = new Socket(ip, 1000); Socket socket = new Socket(); socket.connect(new InetSocketAddress(ip, 1000), 1000); DataInputStream input = new DataInputStream(socket.getInputStream()); String data = input.readUTF(); System.out.println(data); String rspdata[] = data.split(" "); if (!rspdata[2].equals("")) { RemotePeerID = rspdata[2]; return true; } socket.close(); } catch (IOException ex) { System.out.println("Connection failed " + ex.getMessage()); } return false; }
From source file:org.jmxtrans.embedded.util.pool.SocketOutputStreamPoolFactory.java
@Override public SocketOutputStream create(HostAndPort hostAndPort) throws Exception { Socket socket = new Socket(); socket.setKeepAlive(true);//from w w w .ja v a 2s . com socket.connect(new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort()), socketConnectTimeoutInMillis); return new SocketOutputStream(socket); }