Java NIO server development, javanio Server

Source: Internet
Author: User

Java NIO server development, javanio Server
1. Introduction to NIO Class Library 1. Buffer

Buffer is an object that contains data to be written and read.

In NIO, all data is processed in a buffer. When reading data, it directly reads data from the Channel to the buffer. When writing data, it is also written from the buffer zone to the channel.

A buffer is essentially an array, usually a ByteBuffer, or an array of other types. In addition, the buffer provides structured access to data and maintenance of read/write locations.

Shows the inheritance relationship of the Buffer class:

  

2. Channel

A Channel reads and writes network data through a Channel. The difference between a channel and a stream is that the channel is bidirectional (the channel can be used to read and write the latter), and the stream is only moving in one direction.

There are two types of channels: SelectableChannel used for network read/write (ServerSocketChannel and SocketChannel are their subclasses) and FileChannel used for file operations.

The following example shows how to use FileChannel to write data to a file, read data from the file, and copy the file data to another file:

Public class NioTest {public static void main (String [] args) throws IOException {copyFile ();} // copy the private static void copyFile () {FileInputStream in = null; fileOutputStream out = null; try {in = new FileInputStream ("src/main/java/data/in-data.txt "); out = new FileOutputStream ("src/main/java/data/out-data.txt"); FileChannel inChannel = in. getChannel (); FileChannel outChannel = out. getChannel (); ByteBuff Er buffer = ByteBuffer. allocate (1024); int bytesRead = inChannel. read (buffer); while (bytesRead! =-1) {buffer. flip (); outChannel. write (buffer); buffer. clear (); bytesRead = inChannel. read (buffer) ;}} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}/// write the file private static void writeFileNio () {try {RandomAccessFile fout = new RandomAccessFile ("src/main/java/data/nio-dat A.txt "," rw "); FileChannel fc = fout. getChannel (); ByteBuffer buffer = ByteBuffer. allocate (1, 1024); buffer. put ("hi123 ". getBytes (); buffer. flip (); try {fc. write (buffer);} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace () ;}// read the file private static void readFileNio () {FileInputStre Am fileInputStream; try {fileInputStream = new FileInputStream ("src/main/java/data/nio-data.txt"); FileChannel fileChannel = fileInputStream. getChannel (); // get ByteBuffer byteBuffer = ByteBuffer from FileInputStream. allocate (1024); // create a buffer int bytesRead = fileChannel. read (byteBuffer); // read data to the buffer while (bytesRead! =-1) {/* limit = position * position = 0; */byteBuffer. flip (); // hasRemaining (): indicates whether the element while (byteBuffer. hasRemaining () {System. out. print (char) byteBuffer. get ();}/** clear the buffer * position = 0; * limit = capacity; */byteBuffer. clear (); bytesRead = fileChannel. read (byteBuffer) ;}} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
3. multiplexed Selector

Multiplex provides the ability to select ready tasks. Selector continuously polls the Channel registered on it. If a Channel sends a read or write event, the Channel is in the ready state and will be poll by Selector, then, the SelectionKey can be used to obtain the set of ready channels for subsequent I/O operations.

One multiplexing Selector can poll multiple channels at the same time. Because JDK uses epoll instead of the traditional select implementation, it has no limit of 1024/2048 of the maximum connection handle, this means that only one thread is responsible for Selector polling and thousands of clients can be connected. Shows the model:

  

Process a Selector in a single thread. To use Selector, you must register a Channel with Selector and call its select () method. This method will be blocked until a registered channel has an event ready. Once this method is returned, the thread can process these events, such as new connections and data reception.

Note:

1. What select model?

Select is an event trigger mechanism. When a waiting event occurs, it is triggered for processing. It is mostly used by Linux-implemented servers to process the client.

It can detect a group of non-blocking I/O devices in a blocked manner and detect events (such as readable, writable, and output with a high priority ), until a device triggers an event or exceeds the specified wait time. That is, they are not responsible for IO, but to help callers find the currently ready devices.

2. What is the epoll model?

Epoll is designed to split a single select/poll operation into one epoll_create + multiple epoll_ctrl + one wait. In addition, the kernel adds a file system "eventpollfs" for epoll operations. Each or more file descriptors to be monitored have an inode node of the corresponding eventpollfs file system, the main information is stored in the eventpoll struct. Important information of monitored files is stored in the epitem structure. So they are one-to-many relationships.

Ii. NIO server development

  Function Description: Enable the server and send a hello string to each connected client.

To use NIO for server-side development, follow these steps:

1. Create a ServerSocketChannel and configure it to be in non-blocking mode.

    serverSocketChannel = ServerSocketChannel.open();    serverSocketChannel.configureBlocking(false);

2. bind the listener and configure TCP parameters, such as the backlog size.

    serverSocketChannel.socket().bind(new InetSocketAddress(8080));

3. Create an independent I/O thread for polling the Selector

4. Create a Selector, register the previously created ServerSocketChannel to the Selector, and listen to SelectionKey. ACCEPT

  selector=Selector.open();   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

5. Start the I/O thread and run the Selector. select () method in the loop body to poll the ready Channel.

While (true) {try {// select () blocking to at least one channel is ready for the event you registered // if no channel is ready, it is always blocked here // select (long timeout) is the same as select (), except for the maximum blocking timeout Millisecond (parameter ). Selector. select ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace (); break ;}
}

6. When the Channel is in the ready state, you need to judge it. If it is in the OP_ACCEPT state, it indicates that it is accessed by a new client, and ServerSocketChannel is called. the accept () method accepts new clients.

// Return the ready SelectionKey and execute Set <SelectionKey> readKeys = selector iteratively. selectedKeys (); for (Iterator <SelectionKey> it = readKeys. iterator (); it. hasNext ();) {SelectionKey key = it. next (); it. remove (); try {if (key. isAcceptable () {ServerSocketChannel server = (ServerSocketChannel) key. channel (); SocketChannel client = server. accept (); client. configureBlocking (false); client. register (selector, SelectionKey. OP_WRITE);} else if (key. isWritable () {SocketChannel client = (SocketChannel) key. channel (); ByteBuffer buffer = ByteBuffer. allocate (20); String str = "hello"; buffer = ByteBuffer. wrap (str. getBytes (); client. write (buffer); key. cancel () ;}} catch (IOException e) {e. printStackTrace (); key. cancel (); try {key. channel (). close () ;}catch (IOException e1) {// TODO Auto-generated catch block e1.printStackTrace ();}}}

7. Set the newly accessed client link SocketChannel to non-blocking mode and configure other TCP Parameters.

  if(key.isAcceptable())    {        ServerSocketChannel server=(ServerSocketChannel) key.channel();        SocketChannel client=server.accept();        client.configureBlocking(false);        ...    }

8. register the SocketChannel to the Selector and listen to OP_WRITE

  client.register(selector,SelectionKey.OP_WRITE);

9. If the polling Channel is OP_WRITE, it indicates that data is to be written to the SockChannel. A ByteBuffer object is constructed to write data packets.

  else if(key.isWritable())    {        SocketChannel client=(SocketChannel) key.channel();        ByteBuffer buffer=ByteBuffer.allocate(20);        String str="hello";        buffer=ByteBuffer.wrap(str.getBytes());        client.write(buffer);        key.cancel();    } 

The complete code is as follows:

Import java. io. IOException; import java.net. inetSocketAddress; import java. nio. byteBuffer; import java. nio. channels. selectionKey; import java. nio. channels. selector; import java. nio. channels. serverSocketChannel; import java. nio. channels. socketChannel; import java. util. iterator; import java. util. set; public class ServerSocketChannelDemo {public static void main (String [] args) {ServerSocketChannel serverSocke TChannel; Selector selector = null; try {serverSocketChannel = ServerSocketChannel. open (); serverSocketChannel. configureBlocking (false); serverSocketChannel. socket (). bind (new InetSocketAddress (8080); selector = Selector. open (); serverSocketChannel. register (selector, SelectionKey. OP_ACCEPT);} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} while (true) {try {// sele Ct () blocking to at least one channel is ready for the event you registered // if there is no prepared channel, it will be blocked all the time // select (long timeout) like select (), except for the maximum blocking timeout Millisecond (parameter ). Selector. select ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace (); break;} // return the ready SelectionKey, and execute Set <SelectionKey> readKeys = selector iteratively. selectedKeys (); for (Iterator <SelectionKey> it = readKeys. iterator (); it. hasNext ();) {SelectionKey key = it. next (); it. remove (); try {if (key. isAcceptable () {ServerSocketChannel server = (ServerSocketChannel) key. channel (); SocketChannel client = server. accept (); client. configureBlocking (false); client. register (selector, SelectionKey. OP_WRITE);} else if (key. isWritable () {SocketChannel client = (SocketChannel) key. channel (); ByteBuffer buffer = ByteBuffer. allocate (20); String str = "hello"; buffer = ByteBuffer. wrap (str. getBytes (); client. write (buffer); key. cancel () ;}} catch (IOException e) {e. printStackTrace (); key. cancel (); try {key. channel (). close () ;}catch (IOException e1) {// TODO Auto-generated catch block e1.printStackTrace ();}}}}}}View Code

We use telnet localhost 8080 to simulate multiple clients:

  

The program running result is as follows:

  

Iii. References

1. netty authoritative guide (Li linfeng)

  

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.