Last active
December 22, 2015 21:48
-
-
Save jrudolph/6535400 to your computer and use it in GitHub Desktop.
Connecting to unavailable hosts is possible in java with OP_CONNECT, connect, and finishConnect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example; | |
import java.io.IOException; | |
import java.net.InetSocketAddress; | |
import java.nio.channels.SelectionKey; | |
import java.nio.channels.Selector; | |
import java.nio.channels.SocketChannel; | |
public class ConnectionTest { | |
public static final InetSocketAddress unavailableHostAddress = new InetSocketAddress("10.10.10.10", 6666); | |
public static void main(String[] args) throws IOException { | |
SocketChannel ch = SocketChannel.open(); | |
ch.configureBlocking(false); | |
Selector sel = Selector.open(); | |
SelectionKey key = ch.register(sel, SelectionKey.OP_CONNECT); | |
int selected = sel.select(); | |
assert(selected == 1); // wtf 1 | |
assert(key.isConnectable() == true); // wtf 2 | |
System.out.println("Is connectable: "+key.isConnectable()); | |
boolean directlyConnected = ch.connect(unavailableHostAddress); | |
assert(directlyConnected == false); | |
assert(ch.isConnected() == false); | |
assert(ch.isConnectionPending() == true); | |
System.out.println("Directly connected: "+directlyConnected+" ch.isConnected: "+ch.isConnected()+" ch.isConnectionPending: "+ch.isConnectionPending()); | |
// we know, this should succeed because of `key.isConnectable()` | |
boolean finishedConnecting = ch.finishConnect(); | |
assert(finishedConnecting == true); // wtf 3 !!! | |
assert(ch.isConnected() == true); // wtf 4 | |
System.out.println("finishConnect() returned: "+finishedConnecting+" ch.isConnected: "+ch.isConnected()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment