The Java Developers Almanac 1.4


Order this book from Amazon.

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

e179. Using a Selector to Manage Non-Blocking Server Sockets

For more information about selectors, see e176 Using a Selector to Manage Non-Blocking Sockets.

This example creates two server sockets and registers them with a selector. The example then uses the selector to listen for events.

    try {
        // Create the selector
        Selector selector = Selector.open();
    
        // Create two non-blocking server sockets on 80 and 81
        ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
        ssChannel1.configureBlocking(false);
        ssChannel1.socket().bind(new InetSocketAddress(80));
    
        ServerSocketChannel ssChannel2 = ServerSocketChannel.open();
        ssChannel2.configureBlocking(false);
        ssChannel2.socket().bind(new InetSocketAddress(81));
    
        // Register both channels with selector
        ssChannel1.register(selector, SelectionKey.OP_ACCEPT);
        ssChannel2.register(selector, SelectionKey.OP_ACCEPT);
    
        while (true) {
            // Wait for an event
            selector.select();
    
            // Get list of selection keys with pending events
            Iterator it = selector.selectedKeys().iterator();
    
            // Process each key
            while (it.hasNext()) {
                // Get the selection key
                SelectionKey selKey = (SelectionKey)it.next();
    
                // Remove it from the list to indicate that it is being processed
                it.remove();
    
                // Check if it's a connection request
                if (selKey.isAcceptable()) {
                    // Get channel with connection request
                    ServerSocketChannel ssChannel = (ServerSocketChannel)selKey.channel();
    
                    // See e178 Accepting a Connection on a ServerSocketChannel
                    // for an example of accepting a connection request
                }
            }
        }
    } 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
e178. Accepting a Connection on a ServerSocketChannel
e180. Detecting When a Non-Blocking Socket Is Closed by the Remote Host

See also: Byte Buffers    File Locking    Files    Streams   


© 2002 Addison-Wesley.