Sample code Analysis for "Netty Getting Started and practice" 2.NIO

Source: Internet
Author: User
Tags readable
In the last article we introduced the traditional IO network information transmission mode, analyzed the traditional IO network transmission Some shortcomings, below we introduced the new IO Network transmission way, compensates the traditional IO the insufficiency.

Official Introduction to NIO:
The NIO full name Java non-blocking IO refers to the new API provided in jdk1.4 and above, which provides cache-supported data containers for all original types (except Boolean types), which provide a non-blocking, highly scalable network.

Let's start with a code instance. Create a "Cn.com.io.nio" package under the previous "Ioserver" project, and then a new class named "New_io_server":

The code for this class is as follows:
Package Cn.com.io.nio;
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;
	
	public class New_io_server {//channel communication private Selector Selector; /** * Gets a serversocket channel and does some initialization work on the channel * @param Port-bound port number * @throws IOException */public void Initserver
		T port) throws IOException {//Get a serversocket channel Serversocketchannel Serverchannel = Serversocketchannel.open ();
		Sets the channel to Non-blocking serverchannel.configureblocking (false);
		Bind the channel's corresponding serversocket to Port Serverchannel.socket (). Bind (new inetsocketaddress port);
		Get a channel manager This.selector = Selector.open (); Bind the channel manager to the channel and register the Selectionkey.op_accept event for the channel, after registering the event,//When the event arrives, Selector.select () returns if the event does not reach Selector.select ()
	will always block Serverchannel.register (selector, selectionkey.op_accept); }
	
	/** * Use polling to listen for selector whether there are any events that need to be handled and, if so, deal with * @throws IOException */public void Listen () throws ioexception{Sys TEM.OUT.PRINTLN ("Server-side startup succeeded.")
		");
			Polling access selector while (true) {//When the registered event arrives, the method returns; otherwise, the method blocks Selector.select ();
			Gets the iterator for the item selected in Selector, the selected item is the registered event iterator<?> ite = This.selector.selectedKeys (). iterator ();
				while (Ite.hasnext ()) {Selectionkey key = (Selectionkey) ite.next ();
				Deletes the selected key to prevent duplicate processing of ite.remove ();
			Handler (key); /** * Processing Request * @param key * @throws IOException */private void Handler (Selectionkey key) throws Ioex
		ception{if (key.isacceptable ()) {//client requests Connection event handleraccept (key);
		}else if (key.isreadable ()) {//obtained the readable event handlerread (key); /** * Processing connection request * @param key * @throws IOException */private void handleraccept (Selectionkey key) throws
		IOException {//get serversocket Serversocketchannel server = (Serversocketchannel) key.channel (); Get the channel Socketchannel channel = Serve with the client connectionR.accept ();
		
		Set to Non-blocking channel.configureblocking (false);
		SYSTEM.OUT.PRINTLN ("New Client Connection");
		Service-side acknowledgment information to the client Channel.write (bytebuffer.wrap ("Server-side successfully created connection". GetBytes ()));
	After the successful connection with the client, in order to receive the client information, the channel needs to be set Read Permissions Channel.register (This.selector, Selectionkey.op_read); /** * Handles readable events * @param key * @throws IOException */private void Handlerread (Selectionkey key) throws Ioex
		ception {//Gets the socket channel where the event occurred socketchannel channel = (Socketchannel) key.channel ();
		Creates a read buffer (1000 bytes per read) Bytebuffer buffer = bytebuffer.allocate (1000);
		Channel.read (buffer);
		byte[] data = Buffer.array ();
		String msg = new string (data). Trim ();
		
		SYSTEM.OUT.PRINTLN ("Server received information:" +msg);
		Bytebuffer Outbuffer = Bytebuffer.wrap (("Server received message:" +msg). GetBytes ());  Channel.write (Outbuffer)//Send message back to client}/** * Start service Test * @throws IOException */public static void Main (string[)
		args) throws IOException {new_io_server Server = New new_io_server ();
		Server.initserver (10010); Server.listEn (); }
}
In the above code, there are many different APIs than traditional IO, which serversocketchannel similar to traditional IO serversocket, and Socketchannel similar to traditional IO sockets. The selector and selectionkey that appear are equivalent to "selector" and "Select event Type". is used to allow a separate thread to "select" the channel, which makes it easy for a separate threads to manage multiple channels.

Let's briefly analyze the code above:
As you can see in the main method of starting a service, we initially called the Initserver method to initialize the server information and did the following things:
(1) Open a ServerSocket channel and set it to non-blocking
(2) Bind the ServerSocket of the channel to port, which is the port of the service port
(3) Then get a channel manager and register a selectionkey.op_accept event to monitor
Different types of requests that the client sends over.

Then the listen is invoked to monitor the client, and a poll is conducted to listen for selector whether there are any events that need to be handled,
If it does, it is processed.
There are two main types of requests that are being monitored:
(1) Connection request: Client connection request to server
(2) Data reading: The client sends the information to the server, and the server accepts and resolves

Process connection requests for channel fetch and blocking type settings, and set channel Read permissions.
Processing a readable event creates a buffer to read client information.

Image point, the whole process is, the service side (restaurant) initialization of a (waiter) selector (selector, used to serve all clients), register a op_accept key (the boss verbally confessed the waiter to receive the door to come in the new guests), meaning that there is a connection event (guests) , selector needs to handle connection events (reception guests), and listen to the client's various information (establish a connection or a la carte), when accepting the type of connection request (for a seat to prepare a meal), for the client registration (ready to accept the customer order); When accepting the type of reading (customer order), listen to the client (customer ) for specific ordering information.

In NiO, each connection channel can be set to a "non-blocking" state, which means that a single thread can be used to open multiple clients for server-side connectivity, and there is no case where a client has been taking a single thread. We run the above code, using the Telnet test of cmd:

Discovery is a service-side connection that can be connected at the same time.

------Excerpt from: https://www.cnblogs.com/xiaoxi/p/6576588.html------
The following table summarizes the main differences between Java IO and NiO:
IO NIO
Stream-oriented buffer
Blocking IO non-blocking IO
No selector

1. Flow-oriented and buffer-oriented
The first major difference between Java io and NiO is that IO is stream-oriented and NIO is buffer-oriented.
Java io-oriented streaming means that each time one or more bytes are read from the stream until all bytes are read, they are not slowed down anywhere:

In addition, it cannot move data back and forth in the stream. If you need to move data that is read from the stream before and after, you need to first cache it to a buffer.
Java NiO has a slightly different buffer-oriented approach. The data is read to a buffer it handles later, and can be moved back and forth in the buffer when needed. This increases the flexibility in the processing process:

However, you also need to check whether the buffer contains all the data you need to work with. Also, make sure that when more data is read into the buffer, do not overwrite data that has not been processed in the buffer.


2. Blocking and non-blocking io
The various streams of Java Io are blocked. This means that when a thread calls read () or write (), the thread is blocked until some data is read, or the data is fully written. The thread cannot do anything in the meantime:

Non-blocking mode for Java NiO, causes a thread to send requests to read data from a channel, but it can only get the data that is currently available, and if no data is currently available, nothing gets done, rather than keeping the thread blocked, so that the thread can continue to do something else until the data becomes readable.

The same is true for non-blocking writing. A thread requests to write some data to a channel, but does not need to wait for it to be fully written, and the thread can do something else at the same time. Threads typically use non-blocking IO idle time to perform IO operations on other channels, so a single thread can now manage multiple input and output channels (channel).

3, selector (selectors)
The Java NiO selector allows a separate thread to monitor multiple input channels, you can register multiple channels using a selector, and then use a separate thread to "select" the channel: these channels already have the input that can be processed, or select the channel that is ready to be written. This selection mechanism makes it easy for a single thread to manage multiple channels.
------Excerpt from: https://www.cnblogs.com/xiaoxi/p/6576588.html------

For traditional IO and NIO, there are a couple of images on the web that are very good to express:

Our system is equivalent to a restaurant, the door is equivalent to ServerSocket, the customer is the same as the socket client, the waiter is equivalent to each socket client processing thread. When dealing with the client in a multi-threaded situation, the equivalent of a restaurant each guest is equipped with a dedicated waiter, which is a system or a restaurant, is a great expense.

And for NiO:

The system is also likened to a restaurant, the gate equivalent to Serverchannel.socket (). bind (New Inetsocketaddress (10010)), the guest is equivalent to the Socketchannel client, Waiters are the equivalent of threads and selector, and it takes a waiter to serve all the guests, which is a low cost for the system or restaurant.

Reprint please indicate the source: https://blog.csdn.net/acmman/article/details/80039201

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.