Java Code Examples for java.nio.channels.SocketChannel#connect()
The following examples show how to use
java.nio.channels.SocketChannel#connect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IpStation.java From swim with Apache License 2.0 | 6 votes |
@Override default IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) { try { final Station station = station(); final SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); ipSettings.configure(channel.socket()); final boolean connected = channel.connect(remoteAddress); final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress(); final TcpSocket context = new TcpSocket(localAddress, remoteAddress, channel, ipSettings, true); context.become(socket); if (connected) { station.transport(context, FlowControl.WAIT); context.didConnect(); } else { context.willConnect(); station.transport(context, FlowControl.CONNECT); } return context; } catch (IOException | UnresolvedAddressException error) { throw new StationException(remoteAddress.toString(), error); } }
Example 2
Source File: NIOConnector.java From dble with GNU General Public License v2.0 | 6 votes |
private void connect(Selector finalSelector) { AbstractConnection c; while ((c = connectQueue.poll()) != null) { try { SocketChannel channel = (SocketChannel) c.getChannel(); channel.register(finalSelector, SelectionKey.OP_CONNECT, c); channel.connect(new InetSocketAddress(c.host, c.port)); } catch (Exception e) { LOGGER.warn("error:", e); c.close(e.toString()); if (c instanceof MySQLConnection) { ((MySQLConnection) c).onConnectFailed(e); } } } }
Example 3
Source File: UnknownHostTcpTest.java From netcrusher-java with Apache License 2.0 | 6 votes |
@Test public void test() throws Exception { SocketChannel channel = SocketChannel.open(); channel.configureBlocking(true); channel.connect(new InetSocketAddress(HOSTNAME_BIND, PORT_CRUSHER)); try { Assert.assertEquals(0, crusher.getClientAddresses().size()); Thread.sleep(3002); Assert.assertEquals(0, crusher.getClientAddresses().size()); ByteBuffer bb = ByteBuffer.allocate(100); bb.put((byte) 0x01); bb.flip(); try { channel.write(bb); Assert.fail("Exception is expected"); } catch (IOException e) { // } } finally { channel.close(); } }
Example 4
Source File: NioTcpConnector.java From craft-atom with MIT License | 5 votes |
@Override protected Future<Channel<byte[]>> connectByProtocol(SocketAddress remoteAddress, SocketAddress localAddress) throws IOException { SocketChannel sc = null; boolean success = false; try { sc = newSocketChannel(localAddress); if (sc.connect(remoteAddress)) { // return true immediately, as established a local connection, Future<Channel<byte[]>> future = executorService.submit(new ConnectionCall(sc)); success = true; LOG.debug("[CRAFT-ATOM-NIO] Established local connection"); return future; } success = true; } finally { if (!success && sc != null) { try { close(sc); } catch (IOException e) { LOG.warn("[CRAFT-ATOM-NIO] Close exception", e); } } } ConnectionCall cc = new ConnectionCall(sc); FutureTask<Channel<byte[]>> futureTask = new FutureTask<Channel<byte[]>>(cc); cc.setFutureTask(futureTask); connectQueue.add(cc); startup(); selector.wakeup(); return futureTask; }
Example 5
Source File: ReceivingClient.java From nifi with Apache License 2.0 | 5 votes |
private SocketChannel doConnect(InetSocketAddress addressToConnect) throws IOException { SocketChannel channel = SocketChannel.open(); if (channel.connect(addressToConnect)) { channel.configureBlocking(false); channel.register(this.selector, SelectionKey.OP_READ); } else { throw new IllegalStateException("Failed to connect to Server at: " + addressToConnect); } return channel; }
Example 6
Source File: Initiator.java From philadelphia with Apache License 2.0 | 5 votes |
static Initiator open(SocketAddress address) throws IOException { SocketChannel channel = SocketChannel.open(); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); channel.connect(address); channel.configureBlocking(false); return new Initiator(channel); }
Example 7
Source File: SocketChannelTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * @tests SocketChannel#read(ByteBuffer[], int, int) when remote server * closed */ public void test_socketChannel_read_ByteBufferII_remoteClosed() throws Exception { // regression 1 for HARMONY-549 ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(null); SocketChannel sc = SocketChannel.open(); sc.connect(ssc.socket().getLocalSocketAddress()); ssc.accept().close(); ByteBuffer[] buf = { ByteBuffer.allocate(10) }; assertEquals(-1, sc.read(buf, 0, 1)); ssc.close(); sc.close(); }
Example 8
Source File: SelectorTest.java From j2objc with Apache License 2.0 | 5 votes |
private void assert_select_OP_ACCEPT(SelectType type, int timeout) throws IOException, ClosedChannelException { SocketChannel sc = SocketChannel.open(); SocketChannel client = null; try { ssc.register(selector, SelectionKey.OP_ACCEPT); sc.connect(localAddress); int count = blockingSelect(type, timeout); assertEquals(1, count); Set<SelectionKey> selectedKeys = selector.selectedKeys(); assertEquals(1, selectedKeys.size()); SelectionKey key = selectedKeys.iterator().next(); assertEquals(ssc.keyFor(selector), key); assertEquals(SelectionKey.OP_ACCEPT, key.readyOps()); // select again, it should return 0 count = selectOnce(type, timeout); assertEquals(0,count); // but selectedKeys remains the same as previous assertSame(selectedKeys, selector.selectedKeys()); client = ssc.accept(); selectedKeys.clear(); } finally { try { sc.close(); } catch (IOException e) { // do nothing } if (null != client) { client.close(); } } ssc.keyFor(selector).cancel(); }
Example 9
Source File: TestTunnelWithArbitraryTCPTraffic.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@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 { 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); } }
Example 10
Source File: NIOConnector.java From Mycat-NIO with Apache License 2.0 | 5 votes |
private void connect(Selector selector) { Connection c = null; while ((c = connectQueue.poll()) != null) { try { SocketChannel channel = (SocketChannel) c.getChannel(); channel.register(selector, SelectionKey.OP_CONNECT, c); channel.connect(new InetSocketAddress(c.host, c.port)); } catch (Throwable e) { c.close("connect failed:" + e.toString()); } } }
Example 11
Source File: CloseAfterConnect.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 12
Source File: LotsOfCancels.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
private void handleClients() throws Exception { int selectCount = 0; while (true) { int createdCount = 0; synchronized (this) { if (connectionsNeeded > 0) { while (connectionsNeeded > 0 && createdCount < 20) { connectionsNeeded--; createdCount++; totalCreated++; SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(address); if (!channel.finishConnect()) { channel.register(selector, SelectionKey.OP_CONNECT); } } log("Started total of " + totalCreated + " client connections"); Thread.sleep(200); } } if (createdCount > 0) { selector.selectNow(); } else { selectCount++; long startTime = System.nanoTime(); selector.select(); long duration = durationMillis(startTime); log("Exited clientSelector.select(), loop #" + selectCount + ", duration = " + duration + "ms"); } int keyCount = -1; Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); synchronized (key) { keyCount++; keys.remove(); if (!key.isValid()) { log("Ignoring client key #" + keyCount); continue; } int readyOps = key.readyOps(); if (readyOps == SelectionKey.OP_CONNECT) { key.interestOps(0); ((SocketChannel) key.channel()).finishConnect(); } else { log("readyOps() on client key #" + keyCount + " returned " + readyOps); } } } } }
Example 13
Source File: SocketIOWithTimeout.java From big-c with Apache License 2.0 | 4 votes |
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} * with a timeout. * * @see SocketChannel#connect(SocketAddress) * * @param channel - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (Time.now() + timeout): 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel)channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) {} throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
Example 14
Source File: CloseAfterConnect.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 15
Source File: SocketIOWithTimeout.java From stratosphere with Apache License 2.0 | 4 votes |
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout. * * @see SocketChannel#connect(SocketAddress) * @param channel * - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) { throw new SocketTimeoutException(timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) { } throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
Example 16
Source File: LotsOfCancels.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
private void handleClients() throws Exception { int selectCount = 0; while (true) { int createdCount = 0; synchronized (this) { if (connectionsNeeded > 0) { while (connectionsNeeded > 0 && createdCount < 20) { connectionsNeeded--; createdCount++; totalCreated++; SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(address); if (!channel.finishConnect()) { channel.register(selector, SelectionKey.OP_CONNECT); } } log("Started total of " + totalCreated + " client connections"); Thread.sleep(200); } } if (createdCount > 0) { selector.selectNow(); } else { selectCount++; long startTime = System.nanoTime(); selector.select(); long duration = durationMillis(startTime); log("Exited clientSelector.select(), loop #" + selectCount + ", duration = " + duration + "ms"); } int keyCount = -1; Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); synchronized (key) { keyCount++; keys.remove(); if (!key.isValid()) { log("Ignoring client key #" + keyCount); continue; } int readyOps = key.readyOps(); if (readyOps == SelectionKey.OP_CONNECT) { key.interestOps(0); ((SocketChannel) key.channel()).finishConnect(); } else { log("readyOps() on client key #" + keyCount + " returned " + readyOps); } } } } }
Example 17
Source File: CloseAfterConnect.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 18
Source File: CloseAfterConnect.java From openjdk-8 with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }
Example 19
Source File: LotsOfCancels.java From openjdk-8-source with GNU General Public License v2.0 | 4 votes |
private void handleClients() throws Exception { int selectCount = 0; while (true) { int createdCount = 0; synchronized (this) { if (connectionsNeeded > 0) { while (connectionsNeeded > 0 && createdCount < 20) { connectionsNeeded--; createdCount++; totalCreated++; SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(address); if (!channel.finishConnect()) { channel.register(selector, SelectionKey.OP_CONNECT); } } log("Started total of " + totalCreated + " client connections"); Thread.sleep(200); } } if (createdCount > 0) { selector.selectNow(); } else { selectCount++; long startTime = System.nanoTime(); selector.select(); long duration = durationMillis(startTime); log("Exited clientSelector.select(), loop #" + selectCount + ", duration = " + duration + "ms"); } int keyCount = -1; Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); synchronized (key) { keyCount++; keys.remove(); if (!key.isValid()) { log("Ignoring client key #" + keyCount); continue; } int readyOps = key.readyOps(); if (readyOps == SelectionKey.OP_CONNECT) { key.interestOps(0); ((SocketChannel) key.channel()).finishConnect(); } else { log("readyOps() on client key #" + keyCount + " returned " + readyOps); } } } } }
Example 20
Source File: CloseAfterConnect.java From openjdk-8-source with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(0)); InetAddress lh = InetAddress.getLocalHost(); final SocketChannel sc = SocketChannel.open(); final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort()); // establish connection in another thread Runnable connector = new Runnable() { public void run() { try { sc.connect(isa); } catch (IOException ioe) { ioe.printStackTrace(); } } }; Thread thr = new Thread(connector); thr.start(); // wait for connect to be established and for thread to // terminate do { try { thr.join(); } catch (InterruptedException x) { } } while (thr.isAlive()); // check connection is established if (!sc.isConnected()) { throw new RuntimeException("SocketChannel not connected"); } // close channel - this triggered the bug as it attempted to signal // a thread that no longer exists sc.close(); // clean-up ssc.accept().close(); ssc.close(); }