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

Blocking and non-blocking implementation of Icano under JAVA NIO

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

Share

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

This article introduces the relevant knowledge of "blocking and non-blocking implementation of Icano under JAVA NIO". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Current environment

Jdk = = 1.8

Code address

Git address: https://github.com/jasonGeng88/java-network-programming

Knowledge point

The implementation of blocking and non-blocking of Icano under nio

SocketChannel introduction

The principle of Ipaw O Multiplexing

The relationship between event Selector and SocketChannel

Event monitoring type

Byte buffered ByteBuffer data structure

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); / / Icano handles setting 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)) Analysis of the principle of non-blocking implementation of}} nio

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 non-blocking IBO

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 describes the object to which it belongs, OP_READ1

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