The Java Developers Almanac 1.4


Order this book from Amazon.

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

e180. Detecting When a Non-Blocking Socket Is Closed by the Remote Host

The only way to detect that the remote host has closed the connection is to attempt to read or write from the connection. If the remote host properly closed the connection, read() will return -1. If the connection was not terminated normally, read() and write() will throw an exception.

When using a selector to process events from a non-blocking socket, the selector will try to return an OP_READ or OP_WRITE event if the remote host has closed the socket.

    try {
        // Read from socket
        int numBytesRead = socketChannel.read(buf);
    
        if (numBytesRead == -1) {
            // No more bytes can be read from the channel
            socketChannel.close();
        } else {
            // Read the bytes from the buffer
        }
    } catch (IOException e) {
        // Connection may have been closed
    }
    
    try {
        // Write to socket
        int numBytesWritten = socketChannel.write(buf);
    } catch (IOException e) {
        // Connection may have been closed
    }

 Related Examples
e173. Creating a Non-Blocking Socket
e174. Reading from a SocketChannel
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

See also: Byte Buffers    File Locking    Files    Streams   


© 2002 Addison-Wesley.