Java NIO mainly involves the relationship among the Channel, SelectionKey, and Selector classes. The following example shows how to use NIO to process requests :/**
*
*/
Package dongzi.nio.exe rcise. nio;
Import java. io. IOException;
Import java.net. InetSocketAddress;
Import java.net. ServerSocket;
Import java. nio. ByteBuffer;
Import java. nio. channels. ClosedChannelException;
Import java. nio. channels. SelectionKey;
Import java. nio. channels. Selector;
Import java. nio. channels. ServerSocketChannel;
Import java. nio. channels. SocketChannel;
Import java. util. Iterator;
/**
* @ Author kyle
*
*/
Public class SelectSockets {
Private static final int PORT_NUMBER = 1234;
/**
* @ Param args
*/
Public static void main (String [] args ){
New SelectSockets (). go (args );
}
Private void go (String [] args ){
Int port = PORT_NUMBER;
If (args. length> 0 ){
Try {
Port = Integer. parseInt (args [0]);
} Catch (Exception e ){
}
}
System. out. println ("Listening port:" + PORT_NUMBER );
Try {
Selector selector = Selector. open ();
StartServer (port, selector );
While (true ){
Int n = selector. select ();
If (n = 0 ){
Continue;
}
Iterator it = selector. selectedKeys (). iterator ();
While (it. hasNext ()){
SelectionKey key = (SelectionKey) it. next ();
If (key. isAcceptable ()){
ServerSocketChannel server = (ServerSocketChannel) key
. Channel ();
SocketChannel channel = server. accept ();
RegisterChannel (selector, channel, SelectionKey. OP_READ );
SayHello (channel );
}
If (key. isReadable ()){
ReadDataFromChannel (key );
}
}
It. remove ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
Private ByteBuffer buffer = ByteBuffer. allocate (1024 );
Private void readDataFromChannel (SelectionKey key) throws IOException {
Int count = 0;
SocketChannel channel = (SocketChannel) key. channel ();
Buffer. clear ();
While (count = channel. read (buffer)> 0 ){
Buffer. flip ();
While (buffer. hasRemaining ()){
System. out. println (buffer. get ());
}
Buffer. clear ();
}
If (count <0 ){
Channel. close ();
}
}
Private void sayHello (SocketChannel channel) throws IOException {
If (channel = null ){
Return;
}
Buffer. clear ();
ByteBuffer buffer = ByteBuffer. wrap ("Hi, there \ r \ n". getBytes ());
Buffer. flip ();
Channel. write (buffer );
}
Private void registerChannel (Selector selector, SocketChannel channel,
Int opRead) throws IOException {
If (channel = null ){
Return;
}
Channel. configureBlocking (false );
Channel. register (selector, opRead );
}
Private void startServer (int port, Selector selector) throws IOException,
ClosedChannelException {
ServerSocketChannel serverChannel = ServerSocketChannel. open ();
ServerChannel. configureBlocking (false );
ServerSocket serverSocket = serverChannel. socket ();
ServerSocket. bind (new InetSocketAddress (port ));
ServerChannel. register (selector, SelectionKey. OP_ACCEPT );
}
}