Demonstrate asynchronous connection of a SocketChannel. - Java Network

Java examples for Network:Socket Channel

Description

Demonstrate asynchronous connection of a SocketChannel.

Demo Code

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");
  }
}

Result


Related Tutorials