Create SocketChannel from IP address : SocketChannel « Network « Java Tutorial






import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SocketChannel;

public class MainClass {

  public static void main(String[] args) throws Exception {
    int port = 1919;

    SocketAddress address = new InetSocketAddress("127.0.0.1", port);
    SocketChannel client = SocketChannel.open(address);
    ByteBuffer buffer = ByteBuffer.allocate(4);
    IntBuffer view = buffer.asIntBuffer();

    for (int expected = 0;; expected++) {
      client.read(buffer);
      int actual = view.get();
      buffer.clear();
      view.rewind();

      if (actual != expected) {
        System.err.println("Expected " + expected + "; was " + actual);
        break;
      }
      System.out.println(actual);
    }
  }
}








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.