Java examples for Network:Socket Channel
Demonstrate asynchronous connection of a SocketChannel.
import java.net.InetSocketAddress; import java.nio.channels.SocketChannel; public class Main { public static void main(String[] argv) throws Exception { String host = "localhost"; int port = 80; InetSocketAddress addr = new InetSocketAddress(host, port); SocketChannel sc = SocketChannel.open(); sc.configureBlocking(false);//from w w w . j av a 2s . co m System.out.println("initiating connection"); sc.connect(addr); while (!sc.finishConnect()) { doSomethingUseful(); } System.out.println("connection established"); // Do something with the connected socket // The SocketChannel is still nonblocking sc.close(); } private static void doSomethingUseful() { System.out.println("doing something useless"); } }