Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to construct the request Model of JAVA NIO O Multiplexing

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to build the request model of JAVA NIO for multiplexing". In the daily operation, I believe that many people have doubts about how to build the request model of JAVA NIO for multiplexing. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how to build the request model of JAVA NIO for multiplexing". Next, please follow the editor to study!

Current environment

Jdk = = 1.8

Scene

To solve this problem, we found that the culprit is "one thread, one request". If a thread can process multiple requests at the same time, the performance will be greatly improved under high concurrency. Here we use the nio technology in JAVA to implement this model.

Blocking implementation of nio

As to what nio is, it is literally understood as New IO, which is a new implementation method introduced in JDK 1.4 in order to make up for the deficiency in the original Imax O. To put it simply, it provides both blocking and non-blocking implementations of Icano (of course, the default implementation is blocking. ).

Next, let's take a look at how nio is handled in a blocking manner.

Establish a connection

With the experience of the previous socket, our first step must also be to establish a socket connection. It's just that instead of using new socket (), a new concept, SocketChannel, is introduced. It can be seen as a complete class of socket, providing many other features in addition to the relevant functions of Socket, such as the ability to register with selectors, which will be discussed later.

The class diagram is as follows:

Establish the connection code implementation:

/ / initialize socket, establish the binding relationship between socket and channel SocketChannel socketChannel = SocketChannel.open (); / / initialize the remote connection address SocketAddress remote = new InetSocketAddress (this.host, port); / / set blocking, which is also the default, but do not set socketChannel.configureBlocking (true); / / establish connection socketChannel.connect (remote)

Get socket connection

Because it is also an implementation of Ihammer O blocking, the later processing of socket input and output streams is basically the same as the previous one. The only difference is that you need to get the socket connection through channel.

Get socket connection

Socket socket = socketChannel.socket ()

Processing input and output streams

PrintWriter pw = getWriter (socketChannel.socket ()); BufferedReader br = getReader (socketChannel.socket ())

Complete example

Package com.jason.network.mode.nio;import com.jason.network.constant.HttpConstant;import com.jason.network.util.HttpUtil;import java.io.*;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;import java.nio.channels.SocketChannel;public class NioBlockingHttpClient {private SocketChannel socketChannel; private String host Public static void main (String [] args) throws IOException {for (String host: HttpConstant.HOSTS) {NioBlockingHttpClient client = new NioBlockingHttpClient (host, HttpConstant.PORT); client.request ();}} public NioBlockingHttpClient (String host, int port) throws IOException {this.host = host; socketChannel = SocketChannel.open (); socketChannel.socket (). SetSoTimeout (5000) SocketAddress remote = new InetSocketAddress (this.host, port); this.socketChannel.connect (remote);} public void request () throws IOException {PrintWriter pw = getWriter (socketChannel.socket ()); BufferedReader br = getReader (socketChannel.socket ()); pw.write (HttpUtil.compositeRequest (host)); pw.flush (); String msg While ((msg = br.readLine ())! = null) {System.out.println (msg);}} private PrintWriter getWriter (Socket socket) throws IOException {OutputStream out = socket.getOutputStream (); return new PrintWriter (out);} private BufferedReader getReader (Socket socket) throws IOException {InputStream in = socket.getInputStream (); return new BufferedReader (new InputStreamReader (in));}}

Non-blocking implementation of nio

Principle analysis

The blocking implementation of nio is basically similar to using native socket, with little difference.

Let's take a look at where it is really powerful. So far, all we have been doing is blocking IGO. For what is blocking Imax O, see the following figure:

We mainly observe the first three kinds of I _ paw O models in the diagram. As for asynchronous I _ paw O, we generally need to rely on the support of the operating system, which is not discussed here.

As can be seen from the figure, the blocking process mainly occurs in two stages:

Phase one: wait for the data to be ready

Phase 2: copy ready data from the kernel buffer to user space

A copy from kernel to user space is produced here, mainly for system performance optimization. Suppose that the data read from the network card is returned directly to the user space, which is bound to cause frequent system interruptions, because the data read from the network card may not be complete and may come intermittently. Using the kernel buffer as a buffer, waiting for the buffer to have enough data, or after reading, carry out a system interrupt and return the data to the user, so that frequent interrupts can be avoided.

Now that we understand the two stages of blocking in I Pot O, let's get down to business. Take a look at how a thread can handle multiple Igamot calls at the same time. As can be seen from the non-blocking Iamp O in the figure above, only the second phase needs blocking, and we don't need to care about the data waiting process of the first stage. However, the model frequently checks whether it is ready, resulting in invalid CPU processing, but the effect is not good. If there is a similar Hollywood principle-"Don't call us, we'll call you." Such a thread can make multiple Icano calls at the same time without having to wait for data to be ready synchronously. When the data is ready and complete, we will be notified by the event mechanism. Doesn't that make it possible for a single thread to handle multiple IO calls simultaneously? That is, the so-called "Istroke O multiplexing model".

After talking a lot of nonsense, let's actually operate the knife.

Create a selector

From the above analysis, we need to have a selector that listens to all Imax O operations and notifies us in the form of events which Ipicuro is ready.

The code is as follows:

Import java.nio.channels.Selector;...private static Selector selector;static {try {selector = Selector.open ();} catch (IOException e) {e.printStackTrace ();}}

Create a non-blocking Icano

Next, let's create a non-blocking SocketChannel, the code and the blocking implementation type, the only difference is socketChannel.configureBlocking (false).

Note: only code after socketChannel.configureBlocking (false) is non-blocking, and if socketChannel.connect () sets the non-blocking mode, then the connection operation is still blocked.

SocketChannel socketChannel = SocketChannel.open (); SocketAddress remote = new InetSocketAddress (host, port); / / set non-blocking mode socketChannel.configureBlocking (false); socketChannel.connect (remote)

Establish the association between selector and socket

With both the selector and socket created, the next step is to associate the two so that the selector and monitor Socket changes. The association binding is done by actively registering the SocketChannel with the selector, which explains why instead of new Socket (), the socket is created as a SocketChannel.

The code is as follows:

SocketChannel.register (selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE)

In the above code, we register socketChannel with the selector and listen for its connection, readable, and writable events.

The specific event listening types are as follows:

Operation type

Value

Description

Belong to the object

OP_READ

1) {Set keys = selector.selectedKeys (); Iterator it = keys.iterator (); while (it.hasNext ()) {SelectionKey key = (SelectionKey) it.next (); it.remove (); if (key.isAcceptable ()) {accept (key) } else if (key.isWritable ()) {write (key);} else if (key.isReadable ()) {receive (key);}} private void accept (SelectionKey key) throws IOException {SocketChannel socketChannel; ServerSocketChannel channel = (ServerSocketChannel) key.channel () SocketChannel = channel.accept (); / / accept connection request socketChannel.configureBlocking (false); socketChannel.register (selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); InetSocketAddress local = (InetSocketAddress) channel.socket (). GetLocalSocketAddress (); String host = local.getHostName (); int port = local.getPort () System.out.println (String.format ("request address:% SVA% s received successfully!", host, port));} private void write (SelectionKey key) throws IOException {SocketChannel channel = (SocketChannel) key.channel (); InetSocketAddress local = (InetSocketAddress) channel.socket (). GetRemoteSocketAddress (); String host = local.getHostName (); String msg = "hello Client"; channel.write (charset.encode (msg)) System.out.println (msg); key.interestOps (SelectionKey.OP_READ);} private void receive (SelectionKey key) throws IOException {SocketChannel channel = (SocketChannel) key.channel (); ByteBuffer buffer = ByteBuffer.allocate (1024); channel.read (buffer); buffer.flip (); String receiveData = charset.decode (buffer). ToString () If (".equals (receiveData)) {key.cancel (); channel.close (); return;} System.out.println (receiveData);}} this is the end of the study on" how to build a request model for Imax O multiplexing in JAVA NIO ", hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report