Reading from a SocketChannel

See also Creating a Non-Blocking Socket.
// Create a direct buffer to get bytes from socket.
// Direct buffers should be long-lived and be reused as much as possible.
ByteBuffer buf = ByteBuffer.allocateDirect(1024);

try {
    // Clear the buffer and read bytes from socket
    int numBytesRead =;

    if (numBytesRead == -1) {
        // No more bytes can be read from the channel
    } else {
        // To read the bytes, flip the buffer

        // Read the bytes from the buffer ...;
        // see Getting Bytes from a ByteBuffer
} catch (IOException e) {
    // Connection may have been closed