The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.nio  [27 examples] > Sockets  [8 examples]

e174. Reading from a SocketChannel

See also e173 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
        buf.clear();
        int numBytesRead = socketChannel.read(buf);
    
        if (numBytesRead == -1) {
            // No more bytes can be read from the channel
            socketChannel.close();
        } else {
            // To read the bytes, flip the buffer
            buf.flip();
    
            // Read the bytes from the buffer ...;
            // see e159 Getting Bytes from a ByteBuffer
        }
    } catch (IOException e) {
        // Connection may have been closed
    }

 Related Examples
e173. Creating a Non-Blocking Socket
e175. Writing to a SocketChannel
e176. Using a Selector to Manage Non-Blocking Sockets
e177. Creating a Non-Blocking Server Socket
e178. Accepting a Connection on a ServerSocketChannel
e179. Using a Selector to Manage Non-Blocking Server Sockets
e180. Detecting When a Non-Blocking Socket Is Closed by the Remote Host

See also: Byte Buffers    File Locking    Files    Streams   


© 2002 Addison-Wesley.