Java Reference
In-Depth Information
After the channel and selector have been set up, you can wait for events by calling the
selector's select() or select( long ) methods.
The select() method is a blocking method that waits until something has happened on
the channel.
The select( long ) method is a blocking method that waits until something has happened
or the specified number of milliseconds has passed, whichever comes first.
Both select() methods return the number of events that have taken place, or 0 if noth-
ing has happened. You can use a while loop with a call to the select() method as a way
to loop until something happens on the channel.
After an event has taken place, you can find out more about it by calling the selector's
selectedKeys() method, which returns a Set object containing details on each of the
events.
17
Use this Set object as you would any other set, creating an Iterator to move through
the set by using its hasNext() and next() methods.
The call to the set's next() method returns an object that should be cast to a
SelectionKey object. This object represents an event that took place on the channel.
Three methods in the SelectionKey class can be used to identify the key in a client pro-
gram: isReadable() , isWritable() , and isConnectible() . Each returns a boolean
value. (A fourth method is used when you're writing a server: isAcceptable() .)
After you retrieve a key from the set, call the key's remove() method to indicate that you
are going to do something with it.
The last thing to find out about the event is the channel on which it took place. Call the
key's channel() method, which returns the associated SocketChannel .
If one of the events identifies a connection, you must make sure that the connection has
been completed before using the channel. Call the key's isConnectionPending()
method, which returns true if the connection is still in progress and false if it is
complete.
To deal with a connection that is still in progress, you can call the socket's
finishConnect() method, which makes an attempt to complete the connection.
Using a nonblocking socket channel involves the interaction of numerous new classes
from the java.nio and java.net packages.
Search WWH ::




Custom Search