Reading from a SocketChannel : SocketChannel « Network « Java Tutorial






import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    SocketChannel sChannel = SocketChannel.open();
    sChannel.configureBlocking(false);
    sChannel.connect(new InetSocketAddress("hostName", 12345));

    int numBytesRead = sChannel.read(buf);

    if (numBytesRead == -1) {
      sChannel.close();
    } else {
      buf.flip();
    }
  }
}








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.