Creating a Non-Blocking Socket - Java Network

Java examples for Network:Socket Channel

Description

Creating a Non-Blocking Socket

Demo Code


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

public class Main {
  public static void main(String[] args) {
    try {//w  w  w.j a v a2 s .c o  m
      // Create a non-blocking socket channel on port 80
      SocketChannel sChannel = createSocketChannel("hostname.com", 80);

      while (!sChannel.finishConnect()) {
        // Do something else
      }
      // Socket channel is now ready to use
    } catch (IOException e) {
    }

  }

  public static SocketChannel createSocketChannel(String hostName, int port)
      throws IOException {
    // Create a non-blocking socket channel
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);

    // Send a connection request to the server; this method is non-blocking
    sChannel.connect(new InetSocketAddress(hostName, port));
    return sChannel;
  }
}

Related Tutorials