views:

686

answers:

1

I have created a simple server client application using java NIO. I used a single selector there for accepting connection, reading data and writing. But I want an application where 1 selector will be busy in accepting the connection while the 2nd selector will read the data and the 3rd selector will write the data.

Means I donot want to put all the load into single selector.

How to achieve this? Is there any online help

Thanks Deepak.

// 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));

    // Register both channels with selector
    ssChannel1.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();

                // Accepting a Connection on a ServerSocketChannel
                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,

    } else {
        // Use the socket channel to communicate with the client

    }

            }
        }
    }
+1  A: 

It is possible to register a channel with multiple Selectors using register(Selector sel, int ops). You then register different interest ops on each of the selectors:

// After the accepting a connection:
SelectionKey readKey = sChannel.register(readSelector, SelectionKey.OP_READ);

// When you have something to write:
SelectionKey writeKey = sChannel.register(writeSelector, SelectionKey.OP_WRITE);
Nuoji
can you give any sample code
Deepak
No, because this is usually not the way you do it. I assume you already looked at http://rox-xmlrpc.sourceforge.net/niotut/ to read up on basic NIO handling. You can also look at various NIO implementations. My code at http://naga.googlecode.com is free to copy or use.
Nuoji