List of usage examples for java.nio.channels SocketChannel connect
public abstract boolean connect(SocketAddress remote) throws IOException;
From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(enabled = false, timeOut = 15000) public void testTunnelToEchoServerMultiRequest() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {//from w w w . j a va 2s .c om int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); String response1 = readFromSocket(client); client.write(ByteBuffer.wrap("Hello\n".getBytes())); String response2 = readFromSocket(client); client.close(); assertEquals(response1, "Knock Knock\n"); assertEquals(response2, "Hello Hello\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(enabled = false, expectedExceptions = IOException.class) public void testTunnelWhereProxyConnectionToServerFailsWithWriteFirstClient() throws IOException, InterruptedException { MockServer proxyServer = startConnectProxyServer(); final int nonExistentPort = 54321; // hope this doesn't exist! Tunnel tunnel = Tunnel.build("localhost", nonExistentPort, "localhost", proxyServer.getServerSocketPort()); try {/*from w w w . ja va 2s.c om*/ int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.configureBlocking(true); client.connect(new InetSocketAddress("localhost", tunnelPort)); // Might have to write multiple times before connection error propagates back from proxy through tunnel to client for (int i = 0; i < 5; i++) { client.write(ByteBuffer.wrap("Knock\n".getBytes())); Thread.sleep(100); } String response1 = readFromSocket(client); LOG.info(response1); client.close(); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); assertEquals(proxyServer.getNumConnects(), 1); } }
From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(enabled = false, timeOut = 15000) public void testTunnelThreadDeadAfterClose() throws IOException, InterruptedException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", talkFirstEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {/*w w w.jav a 2 s. co m*/ int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); String response0 = readFromSocket(client); LOG.info(response0); // write a lot of data to increase chance of response after close for (int i = 0; i < 1000; i++) { client.write(ByteBuffer.wrap("Knock\n".getBytes())); } // don't wait for response client.close(); assertEquals(response0, "Hello\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(enabled = false, timeOut = 15000, expectedExceptions = IOException.class) public void testTunnelThreadDeadAfterUnexpectedException() throws IOException, InterruptedException { MockServer proxyServer = startConnectProxyServer(false, false, 8); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); String response = ""; try {//from w w w.j a v a2 s . c o m int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); response = readFromSocket(client); LOG.info(response); for (int i = 0; i < 5; i++) { client.write(ByteBuffer.wrap("Hello\n".getBytes())); Thread.sleep(100); } client.close(); } finally { proxyServer.stopServer(); tunnel.close(); assertNotEquals(response, "Knock Knock\n"); assertEquals(proxyServer.getNumConnects(), 1); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:org.apache.gobblin.tunnel.TunnelTest.java
@Test(enabled = false) public void mustHandleClientDisconnectingWithoutClosingTunnel() throws Exception { mockExample();// ww w . j a va 2s.c om Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT); try { int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer .wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes())); client.close(); assertNotNull(fetchContent(tunnelPort)); } finally { tunnel.close(); } }
From source file:org.apache.hadoop.hdfs.web.TestWebHdfsTimeouts.java
/** * Consumes the test server's connection backlog by spamming non-blocking * SocketChannel client connections. We never do anything with these sockets * beyond just initiaing the connections. The method saves a reference to each * new SocketChannel so that it can be closed during tearDown. We define a * very small connection backlog, but the OS may silently enforce a larger * minimum backlog than requested. To work around this, we create far more * client connections than our defined backlog. * // www. j ava 2 s .c o m * @throws IOException thrown for any I/O error */ private void consumeConnectionBacklog() throws IOException { for (int i = 0; i < CLIENTS_TO_CONSUME_BACKLOG; ++i) { SocketChannel client = SocketChannel.open(); client.configureBlocking(false); client.connect(nnHttpAddress); clients.add(client); } }
From source file:org.apache.htrace.impl.PackedBufferManager.java
private SelectionKey doConnect() throws IOException { SocketChannel sock = SocketChannel.open(); SelectionKey sockKey = null;/* w w w. j ava2s.c o m*/ boolean success = false; try { if (sock.isBlocking()) { sock.configureBlocking(false); } InetSocketAddress resolvedEndpoint = new InetSocketAddress(conf.endpoint.getHostString(), conf.endpoint.getPort()); resolvedEndpoint.getHostName(); // trigger DNS resolution sock.connect(resolvedEndpoint); sockKey = sock.register(selector, SelectionKey.OP_CONNECT, sock); long startMs = TimeUtil.nowMs(); long remainingMs = conf.connectTimeoutMs; while (true) { selector.select(remainingMs); for (SelectionKey key : selector.keys()) { if (key.isConnectable()) { SocketChannel s = (SocketChannel) key.attachment(); s.finishConnect(); if (LOG.isTraceEnabled()) { LOG.trace("Successfully connected to " + conf.endpointStr + "."); } success = true; return sockKey; } } remainingMs = updateRemainingMs(startMs, conf.connectTimeoutMs); if (remainingMs == 0) { throw new IOException("Attempt to connect to " + conf.endpointStr + " timed out after " + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms."); } } } finally { if (!success) { if (sockKey != null) { sockKey.cancel(); } sock.close(); } } }
From source file:org.cloudata.core.commitlog.CommitLogClient.java
private TransactionData[] readDataFrom(Method readMethod, int index, String tabletName) throws IOException { int port = -1; int replicaCount = rpcUtil.getMultiRpcCount(); for (int count = 0; count < replicaCount; count++) { try {/* w w w.j a v a 2 s.c om*/ port = (Integer) rpcUtil.singleCall(readMethod, index, tabletName); if (port > 0) { break; } } catch (IOException e) { LOG.info("Exception in reading commit log data : " + e); } if (++index % replicaCount == 0) { index = 0; } } if (port < 0) { return null; } SocketChannel socketChannel = SocketChannel.open(); List<TransactionData> txDataList = null; try { socketChannel.connect(new InetSocketAddress(rpcUtil.getAddressAt(index), port)); DataInputStream dis = new DataInputStream( new BufferedInputStream(socketChannel.socket().getInputStream(), 8192)); txDataList = readTxDataFrom(tabletName, dis); } finally { socketChannel.socket().close(); socketChannel.close(); } return txDataList.toArray(new TransactionData[0]); }
From source file:org.cryptomator.ui.util.SingleInstanceManager.java
/** * Checks if there is a valid port at/*from w ww . j a va2 s . com*/ * {@link Preferences#userNodeForPackage(Class)} for {@link Main} under the * given applicationKey, tries to connect to the port at the loopback * address and checks if the port identifies with the applicationKey. * * @param applicationKey * key used to load the port and check the identity of the * connection. * @return */ public static Optional<RemoteInstance> getRemoteInstance(String applicationKey) { Optional<Integer> port = getSavedPort(applicationKey); if (!port.isPresent()) { return Optional.empty(); } SocketChannel channel = null; boolean close = true; try { channel = SocketChannel.open(); channel.configureBlocking(false); LOG.info("connecting to instance {}", port.get()); channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), port.get())); SocketChannel fChannel = channel; if (!TimeoutTask.attempt(t -> fChannel.finishConnect(), 1000, 10)) { return Optional.empty(); } LOG.info("connected to instance {}", port.get()); final byte[] bytes = applicationKey.getBytes(); ByteBuffer buf = ByteBuffer.allocate(bytes.length); tryFill(channel, buf, 1000); if (buf.hasRemaining()) { return Optional.empty(); } buf.flip(); for (int i = 0; i < bytes.length; i++) { if (buf.get() != bytes[i]) { return Optional.empty(); } } close = false; return Optional.of(new RemoteInstance(channel)); } catch (Exception e) { return Optional.empty(); } finally { if (close) { IOUtils.closeQuietly(channel); } } }
From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java
private void startClient(int n, SocketAddress serverAddress, final int clientIntervalMs, final int payloadSize) throws IOException, ExecutionException, InterruptedException, TimeoutException { SocketChannel toServer = SocketChannel.open(); toServer.socket().setKeepAlive(true); toServer.socket().setTcpNoDelay(true); toServer.configureBlocking(true);//from w w w . jav a 2 s. c om toServer.connect(serverAddress); HashMap<String, String> headers = new HashMap<String, String>(); String clientName = runtimeMXBean.getName() + "-client-" + n; headers.put(JnlpConnectionState.CLIENT_NAME_KEY, clientName); headers.put(JnlpConnectionState.SECRET_KEY, secretFor(clientName)); final Channel clientChannel = handler.connect(toServer.socket(), headers, clientListener).get(15, TimeUnit.SECONDS); timer[n % timer.length].scheduleAtFixedRate(new TimerTask() { long start = System.currentTimeMillis(); int index = 0; int times = 0; private NoOpCallable callable = new NoOpCallable(payloadSize == -1 ? null : new byte[payloadSize]); @Override public void run() { try { long start = System.currentTimeMillis(); clientChannel.call(callable); if (config.client != null) { NoOpCallable.noops.incrementAndGet(); } times++; if (times % 1000 == 0) { System.out .println(String.format(" %s has run %d No-op callables. Rate %.1f/s expect %.1f/s", clientChannel.getName(), times, times * 1000.0 / (System.currentTimeMillis() - this.start), 1000.0 / clientIntervalMs)); } long duration = System.currentTimeMillis() - start; if (duration > 250L) { System.err.println(String.format(" %s took %dms to complete a callable", clientChannel.getName(), duration)); } if (callable.payload != null && callable.payload.length > 0) { // mutate the payload to prevent compression int count = callable.payload.length; if (count > 100) { count = 100; } for (int j = 0; j < count; j++) { callable.payload[index] = (byte) (callable.payload[index] * 31 + times); index = Math.abs(index + 1) % callable.payload.length; } } } catch (Exception e) { e.printStackTrace(System.err); IOUtils.closeQuietly(clientChannel); cancel(); System.exit(2); } } }, entropy.nextInt(clientIntervalMs), clientIntervalMs); }