Java NIO simple and classic example

Source: Internet
Author: User

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

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.