The Java Developers Almanac 1.4


Order this book from Amazon.

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

e178. Accepting a Connection on a ServerSocketChannel

To create a ServerSocketChannel, see e177 Creating a Non-Blocking Server Socket.
    // Get port that received the connection request; this information
    // might be useful in determining how to handle the connection
    int localPort = serverSocketChannel.socket().getLocalPort();
    
    try {
        // Accept the connection request.
        // If serverSocketChannel is blocking, this method blocks.
        // The returned channel is in blocking mode.
        SocketChannel sChannel = serverSocketChannel.accept();
    
        // If serverSocketChannel is non-blocking, sChannel may be null
        if (sChannel == null) {
            // There were no pending connection requests; try again later.
            // To be notified of connection requests,
            // see e179 Using a Selector to Manage Non-Blocking Server Sockets.
        } else {
            // Use the socket channel to communicate with the client
            // See e176 Using a Selector to Manage Non-Blocking Sockets.
        }
    } catch (IOException e) {
    }

 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
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.