|
New I/0 Functionality for JavaTM 2 Standard Edition 1.4(10) Once something interesting happens, you have to figure out what happened and respond accordingly. For the channel registered here with the selector, you eXPressed interest in both the OP_CONNECT and OP_READ operations, so you know it can only be one of those events. So, what you do is get the Set of ready objects through the selectedKeys method, and iterate. The element in the Set is a SelectionKey, and you can check if it isConnectable or isReadable for the two states of interest. Here's the basic framework of the loop so far: while (selector.select(500) > 0) {// Get set of ready objectsSet readyKeys = selector.selectedKeys();Iterator readyItor = readyKeys.iterator();// Walk through setwhile (readyItor.hasNext()) { // Get key from set SelectionKey key = (SelectionKey)readyItor.next(); // Remove current entry readyItor.remove(); // Get channel SocketChannel keyChannel = (SocketChannel)key.channel(); if (key.isConnectable()) { } else if (key.isReadable()) { }}}The remove method call requires a little eXPlanation. The ready set of channels can change while you are processing them. So, you should remove the one you are processing when you process it. There's also a timeout setup here for the select call so it doesn't wait forever if there is nothing to do. There's also a call to get the channel from the key in there. You'll need that for each operation. For the sample program here you're doing the equivalent of reading from an HTTP connection, so upon connection you need to send the initial HTTP request. Basically, once you know the connection is made, you send a GET request for the root of the site. When the selector reports that the channel is connectable, it may not have finished connecting yet. So, you should always check if the connection is pending through isConnectionPending and call finishConnect if it is. Once connected, you can write to the channel, but must use a ByteBuffer, not the more familiar I/O streams.
|