Demonstrate asynchronous connection of a SocketChannel : SocketChannel « Network « Java Tutorial






import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;


public class MainClass {
  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);

    System.out.println("initiating connection");

    sc.connect(addr);

    while (!sc.finishConnect()) {
      System.out.println("doing something useless");
    }

    System.out.println("connection established");

    sc.close();
  }

}








19.13.SocketChannel
19.13.1.Create SocketChannel from IP address
19.13.2.Reading from a SocketChannel
19.13.3.Writing to a SocketChannel
19.13.4.Channel selector
19.13.5.Use SocketChannel to get Web page
19.13.6.Demonstrate asynchronous connection of a SocketChannel
19.13.7.Creating a Non-Blocking Socket: requires a socket channel.