In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
Java NIO use and principle analysis is what, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
You can finally get into the most interesting part of NIO, non-blocking Imax O. Usually when you do a synchronous Istroke O operation, if you read the data, the code blocks until there is data available to read. Similarly, the write call will block until the data can be written. The traditional Server/Client pattern is based on TPR (Thread per Request), and the server sets up a thread for each client request, which is responsible for processing a single client request. One of the problems caused by this mode is the sharp increase in the number of threads, a large number of threads will increase the overhead of the server. In order to avoid this problem, most implementations adopt the thread pool model and set the maximum number of threads in the thread pool, which brings a new problem. If there are 200 threads in the thread pool and 200 users are downloading large files, the request of the 201th user can not be processed in time, even if the 201th user only wants to request a page of several KB size. The traditional Server/Client mode is shown in the following figure:
Non-blocking iAccord O in NIO works based on Reactor mode. The invocation will not be blocked. On the contrary, it registers specific iUnip O events of interest, such as readable data arrival, new socket connections, etc., and the system will notify us when specific events occur. The core object for implementing non-blocking iAccord O in NIO is Selector,Selector, which registers various IAccord O events, and when those events occur, it is this object that tells us what happened, as shown in the following figure:
As can be seen from the figure, when any registered event such as read or write occurs, the corresponding SelectionKey can be obtained from the Selector. At the same time, the event and the specific SelectableChannel of the event can be found from the SelectionKey to obtain the data sent by the client. About SelectableChannel, you can refer to the use and principle analysis of Java NIO (1)
Writing a server handler using non-blocking Istroke O in NIO can be roughly divided into the following three steps:
1. Register events of interest with the Selector object
two。 Get interesting events from Selector
3. Deal with it according to different events
Next, let's use a simple example to illustrate the whole process. The first is to register the events of interest with the Selector object:
[java] view plain copy
Print?
/ *
* Registration event
* * /
Protected Selector getSelector () throws IOException {
/ / create a Selector object
Selector sel = Selector.open ()
/ / create a selectable channel and configure it in non-blocking mode
ServerSocketChannel server = ServerSocketChannel.open ()
Server.configureBlocking (false)
/ / bind the channel to the specified port
ServerSocket socket = server.socket ()
InetSocketAddress address = new InetSocketAddress (port)
Socket.bind (address)
/ / register the events of interest with Selector
Server.register (sel, SelectionKey.OP_ACCEPT)
Return sel
}
The ServerSocketChannel object is created, and the configureBlocking () method is called to configure the non-blocking mode. The next three lines of code bind the channel to the specified port, and finally register the event with Selector. Here, the parameter specified is OP_ACCEPT, that is, we specify that we want to listen for the accept event, that is, the event generated when the new connection is generated. For the ServerSocketChannel channel, the only parameter we can specify is OP_ACCEPT.
Get the events of interest from Selector, that is, start listening and enter the internal loop:
[java] view plain copy
Print?
/ *
* start listening
* * /
Public void listen () {
System.out.println ("listen on" + port)
Try {
While (true) {
/ / the call blocks until at least one event occurs.
Selector.select ()
Set keys = selector.selectedKeys ()
Iterator iter = keys.iterator ()
While (iter.hasNext ()) {
SelectionKey key = (SelectionKey) iter.next ()
Iter.remove ()
Process (key)
}
}
} catch (IOException e) {
E.printStackTrace ()
}
}
The internal loop pattern basically follows this approach in non-blocking IDUBO. The select () method is called first, which blocks until at least one event occurs, then uses the selectedKeys () method to get the SelectionKey where the event occurred, and then loops with an iterator.
The final step is to write the corresponding handling code according to different events:
[java] view plain copy
Print?
/ *
* handle according to different events
* * /
Protected void process (SelectionKey key) throws IOException {
/ / receive the request
If (key.isAcceptable ()) {
ServerSocketChannel server = (ServerSocketChannel) key.channel ()
SocketChannel channel = server.accept ()
Channel.configureBlocking (false)
Channel.register (selector, SelectionKey.OP_READ)
}
/ / read the information
Else if (key.isReadable ()) {
SocketChannel channel = (SocketChannel) key.channel ()
Int count = channel.read (buffer)
If (count > 0) {
Buffer.flip ()
CharBuffer charBuffer = decoder.decode (buffer)
Name = charBuffer.toString ()
SelectionKey sKey = channel.register (selector, SelectionKey.OP_WRITE)
SKey.attach (name)
} else {
Channel.close ()
}
Buffer.clear ()
}
/ / write events
Else if (key.isWritable ()) {
SocketChannel channel = (SocketChannel) key.channel ()
String name = (String) key.attachment ()
ByteBuffer block = encoder.encode (CharBuffer.wrap ("Hello" + name))
If (block! = null)
{
Channel.write (block)
}
Else
{
Channel.close ()
}
}
}
Here we judge whether to accept the request, read the data or write the event, and deal with it differently.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.