List of usage examples for java.nio.channels SocketChannel connect
public abstract boolean connect(SocketAddress remote) throws IOException;
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testTunnelToDelayedEchoServer() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", delayedDoubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {/*from ww w .j av a 2 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())); String response = readFromSocket(client); client.close(); assertEquals(response, "Knock Knock\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testDirectConnectionToEchoServer() throws IOException { SocketChannel client = SocketChannel.open(); try {//w w w . j a v a 2 s . c o m client.connect(new InetSocketAddress("localhost", doubleEchoServer.getServerSocketPort())); writeToSocket(client, "Knock\n".getBytes()); String response = readFromSocket(client); client.close(); assertEquals(response, "Knock Knock\n"); } finally { client.close(); } }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testTunnelToEchoServerMultiRequest() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {/* 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())); 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:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testTunnelThreadDeadAfterClose() throws IOException, InterruptedException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", talkFirstEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {//from w w w. j a v a2s .c o 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:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(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 a2s . 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:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(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 {/* w w w . j av a 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:com.mobicage.rpc.newxmpp.XMPPConfigurationFactory.java
public ConnectionConfiguration getSafeXmppConnectionConfiguration(final String xmppServiceName, final String email, final boolean hasFailed) throws XMPPConfigurationException { debuglog("Creating new XMPP connection"); if (!mConnectivityManager.isConnected()) { debuglog("No network."); throw new XMPPConfigurationException("No network."); }//from ww w . ja va 2s. com final ConnectionConfiguration xmppConfig; if (hasFailed) { debuglog("Getting config from cloud because previous connection attempt failed."); xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email); } else { debuglog("Getting config from config provider."); ConnectionConfiguration tmpXmppConfig = getBasicXMPPConfigurationFromConfigProvider(xmppServiceName); if (tmpXmppConfig == null) { debuglog("Getting config from cloud because config provider is empty."); xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email); } else xmppConfig = tmpXmppConfig; } if (xmppConfig == null) { debuglog("No xmpp configuration found."); throw new XMPPConfigurationException("No xmpp configuration found."); } final HostAddress[] hostAddresses = xmppConfig.getHosts(); if (hostAddresses.length == 0) { debuglog("Error: did not receive any XMPP DNS SRV record"); throw new XMPPConfigurationException("Did not find any XMPP DNS SRV record"); } else if (hostAddresses.length == 1 && xmppServiceName.equals(hostAddresses[0].getHost()) && XMPP_DEFAULT_PORT == hostAddresses[0].getPort()) { buglog("Using fallback value for DNS SRV (but network is up): " + hostAddresses[0]); } debuglog("Found XMPP DNS SRV records:"); for (int i = hostAddresses.length - 1; i >= 0; i--) { debuglog("- host = " + hostAddresses[i]); } final int preferredXMPPPort = hostAddresses[hostAddresses.length - 1].getPort(); debuglog("Preferred XMPP port is " + preferredXMPPPort); // Do non-blocking TCP connect attempts Map<HostAddress, SocketChannel> allChannels = new HashMap<HostAddress, SocketChannel>(); Map<HostAddress, SocketChannel> remainingChannels = new HashMap<HostAddress, SocketChannel>(); for (int i = hostAddresses.length - 1; i >= 0; i--) { final HostAddress ha = hostAddresses[i]; try { SocketChannel sChannel = SocketChannel.open(); allChannels.put(ha, sChannel); sChannel.configureBlocking(false); sChannel.connect(new InetSocketAddress(ha.getHost(), ha.getPort())); remainingChannels.put(ha, sChannel); } catch (IOException e) { // Cannot connect to one socket ; let's not drop others debuglog("Ignoring socket due to connection error: " + ha); } } if (remainingChannels.size() == 0) { debuglog("Error: could not connect to any of the XMPP DNS SRV records"); debuglog("Closing attempted TCP sockets"); for (SocketChannel sc : allChannels.values()) { try { sc.close(); } catch (IOException e) { } } debuglog("All attempted TCP sockets are closed now"); throw new XMPPConfigurationException("Error: could not connect to any of the XMPP DNS SRV records"); } final long starttime = SystemClock.elapsedRealtime(); HostAddress goodHostAddress = null; while (true) { Iterator<Entry<HostAddress, SocketChannel>> iter = remainingChannels.entrySet().iterator(); while (iter.hasNext()) { Entry<HostAddress, SocketChannel> e = iter.next(); final HostAddress ha = e.getKey(); final SocketChannel sc = e.getValue(); try { if (sc.finishConnect()) { if (sc.isConnected()) { debuglog("Successful TCP connection to " + ha); iter.remove(); if (goodHostAddress != null) { // We already found a host // Pick this better one only if the one we found already was not using the // preferred XMPP port, and the new one does have the preferred XMPP port if (goodHostAddress.getPort() != preferredXMPPPort && ha.getPort() == preferredXMPPPort) { goodHostAddress = ha; debuglog("Found better host " + goodHostAddress); } else { debuglog("Old host was better: " + goodHostAddress); } } else { goodHostAddress = ha; debuglog("Selecting host " + goodHostAddress); } } else { debuglog("Failed TCP connection to " + ha); iter.remove(); } } } catch (IOException ex) { // Error during finishConnect() debuglog("TCP connection timeout to " + ha); iter.remove(); } } final long now = SystemClock.elapsedRealtime(); if (goodHostAddress != null && goodHostAddress.getPort() == preferredXMPPPort) { debuglog("Found responsive XMPP host with preferred port " + preferredXMPPPort); break; } if (remainingChannels.size() == 0) { debuglog("No more XMPP hosts to check"); break; } if (now > starttime + XMPP_MAX_CONNECT_MILLIS) { debuglog("Timeout trying to find responsive XMPP host"); break; } if (goodHostAddress != null) { if (now > starttime + XMPP_MAX_TRY_PREFERRED_PORT_MILLIS) { // XXX: would be better to wait at most N seconds (e.g. 2) AFTER the first successful connection // happened (to a non preferred port) debuglog("Give up looking for responsive XMPP host with preferred port."); break; } boolean stillWaitingForConnectionWithPreferredPort = false; for (HostAddress ha : remainingChannels.keySet()) { if (ha.getPort() == preferredXMPPPort) { stillWaitingForConnectionWithPreferredPort = true; break; } } if (!stillWaitingForConnectionWithPreferredPort) { debuglog("No more responsive XMPP hosts with preferred port to wait for."); break; } } debuglog("Sleeping " + XMPP_POLLING_INTERVAL_MILLIS + "ms while trying to connect to XMPP"); try { Thread.sleep(XMPP_POLLING_INTERVAL_MILLIS); } catch (InterruptedException ex) { throw new XMPPConfigurationException("Interrupt during Thread.sleep()"); } } debuglog("Closing attempted TCP sockets"); for (SocketChannel sc : allChannels.values()) { try { sc.close(); } catch (IOException e) { } } debuglog("All attempted TCP sockets are closed now"); if (goodHostAddress == null) { debuglog("Did not find a good host address and hasfailed: " + hasFailed); clearSRVConfig(); if (hasFailed) throw new XMPPConfigurationException("Could not connect to any of the XMPP targets"); else return getSafeXmppConnectionConfiguration(xmppServiceName, email, true); } debuglog("Using XMPP host " + goodHostAddress); xmppConfig.setHosts(new HostAddress[] { goodHostAddress }); return xmppConfig; }
From source file:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Ouverture de la socket.//w w w . ja v a 2s.co m * * @return la socket * @throws ClamAVException * the clam av exception */ private SocketChannel openSocket() throws ClamAVException { SocketChannel channel = null; try { // Rcuperation de la socket depuis le pool channel = this.socketPool.borrowObject(); if (!channel.isOpen()) { channel = SocketChannel.open(); } if (!channel.isConnected()) { channel.configureBlocking(true); channel.connect(new InetSocketAddress(this.clamAVServer, this.clamAVPort)); } } catch (final Exception e) { ClamAVCheckService.LOGGER.error("Unable to borrow socket from pool", e); throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e); } return channel; }
From source file:edu.hawaii.soest.kilonalu.ctd.SBE37Source.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *//* w w w .ja va 2 s. c o m*/ protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); //dataSocket.configureBlocking(false); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { System.err.println("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { System.err.println("Couldn't get I/O connection to: " + host); disconnect(); dataSocket = null; } catch (Exception e) { disconnect(); dataSocket = null; } return dataSocket; }
From source file:edu.hawaii.soest.kilonalu.adcp.ADCPSource.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *///from w ww . jav a 2s.c om protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { System.err.println("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { System.err.println("Couldn't get I/O connection to: " + host); disconnect(); dataSocket = null; } catch (Exception e) { disconnect(); dataSocket = null; } return dataSocket; }