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 create Netty client access process NioSocketChannel

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

Share

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

This article mainly shows you "how to create Netty client access process NioSocketChannel". The content is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and learn this article "how to create Netty client access process NioSocketChannel".

The creation of NioSocketChannel goes back to the read () method public void read () in the previous section {/ / must be called by the NioEventLoop method and cannot be called by an external thread assert eventLoop (). InEventLoop (); / / server channel config final ChannelConfig config = config (); / / server channel pipeline final ChannelPipeline pipeline = pipeline (); / / server access rate final RecvByteBufAllocator.Handle allocHandle = unsafe (). RecvBufAllocHandle () / / set configuration allocHandle.reset (config); boolean closed = false; Throwable exception = null; try {try {do {/ / create the underlying channel / / readBuf of jdk to temporarily host the read link int localRead = doReadMessages (readBuf); if (localRead = = 0) {break } if (localRead < 0) {closed = true; break;} / / the allocator counts the read links allocHandle.incMessagesRead (localRead) / / whether the number of connections exceeds the maximum} while (allocHandle.continueReading ());} catch (Throwable t) {exception = t;} int size = readBuf.size (); / / traverses each client connection for (int I = 0; I < size; I + +) {readPending = false / / pass the event, which will create a NioSokectChannel to pass / / eventually call the channelRead () method pipeline.fireChannelRead (readBuf.get (I)) of ServerBootstrap's inner class ServerBootstrapAcceptor;} readBuf.clear (); allocHandle.readComplete (); pipeline.fireChannelReadComplete (); / / Code ellipsis} finally {/ / Code ellipsis}

Let's continue to analyze the logic of int localRead = doReadMessages (readBuf).

Let's first look at readBufprivate final List readBuf = new ArrayList ()

Here we simply define an ArrayList, and the doReadMessages (readBuf) method is to put the read link in this list, because this is NioServerSocketChannel, so this goes to the doReadMessage () method of NioServerSocketChannel.

Follow to the doReadMessage () method:

Protected int doReadMessages (List buf) throws Exception {/ / based on the current jdk underlying serverSocketChannel, get the jdk underlying channel SocketChannel ch = javaChannel (). Accept (); try {if (ch! = null) {/ / encapsulated into a NioSokectChannel and thrown into buf buf.add (new NioSocketChannel (this, ch)); return 1 }} catch (Throwable t) {/ / Code omitted} return 0;} jdk underlying related content

First of all, get the Channel of jdk according to jdk's ServerSocketChannel, and the little friends who are familiar with Nio should be no stranger.

Encapsulate it into a NioSokectChannel and throw it into the Readbuf

The NioSocketChannel here wraps the underlying SocketChannel of the jdk. We see that its constructor passes two parameters, this for the current NioServerSocketChannel and ch for the SocketChannel of the jdk.

Let's follow up on the construction method of NioSocketChannel:

Public NioSocketChannel (Channel parent, SocketChannel socket) {super (parent, socket); config = new NioSocketChannelConfig (this, socket.socket ());}

Here you can see that the parent class constructor is called, passing in two parameters, parent for the creation of its own channel, NioServerSocketChannel and socket for the underlying socketChannel of the jdk.

Follow protected AbstractNioByteChannel (Channel parent, SelectableChannel ch) {super (parent, ch, SelectionKey.OP_READ);} in the parent constructor

Where SelectionKey.OP_READ represents its listening event is a read event

Continue with the constructor of the parent class:

Protected AbstractNioChannel (Channel parent, SelectableChannel ch, int readInterestOp) {super (parent); this.ch = ch; this.readInterestOp = readInterestOp; try {/ / set to non-blocking ch.configureBlocking (false);} catch (IOException e) {/ / Code ellipsis}}

Here we initialize its own member variable ch, which is the underlying SocketChannel of jdk, and initialize its own listening event readInterestOp, that is, the read event

Ch.configureBlocking (false) is no stranger to those who are familiar with nio, that is, setting the SocketChannel of jdk to non-blocking.

Let's move on to the parent constructor:

Protected AbstractChannel (Channel parent) {this.parent = parent; id = newId (); unsafe = newUnsafe (); pipeline = newChannelPipeline ();}

Here you initialize parent, that is, create your own NioServerSocketChannel and create a unique id for yourself.

Initialize the unsafe, and we follow the newUnsafe () method

Because this method is called by NioEventLoop, it goes to the newUnsafe () of its parent class AbstractNioByteChannel

Follow to newUnsafe ():

Protected AbstractNioUnsafe newUnsafe () {return new NioByteUnsafe ();}

The NioByteUnsafe object is created here, so the unsafe corresponding to NioSocketChannel is NioByteUnsafe

As we move on, we see that it initializes pipeline, and we'll talk about pipline in the next chapter.

Go back to the constructor in NioSocketChannel:

Public NioSocketChannel (Channel parent, SocketChannel socket) {super (parent, socket); config = new NioSocketChannelConfig (this, socket.socket ());}

Like NioServerSocketChannel, a Config property is initialized, passing in two parameters, the current NioSocketChannel itself and the socket object of the underlying SocketChannel of jdk

We follow up its construction method private NioSocketChannelConfig (NioSocketChannel channel, Socket javaSocket) {super (channel, javaSocket);}

Again, this class is the inner class of NioSocketChannel

Continue to construct methods with the parent class:

Public DefaultSocketChannelConfig (SocketChannel channel, Socket javaSocket) {super (channel); if (javaSocket = = null) {throw new NullPointerException ("javaSocket");} / / Save current javaSocket this.javaSocket = javaSocket; / / whether to disable Nagle algorithm if (PlatformDependent.canEnableTcpNoDelayByDefault ()) {try {setTcpNoDelay (true);} catch (Exception e) {}

The socket object of SocketChannel is saved here, and the Nagle algorithm is prohibited by default. Students who are interested in Nagle can learn the relevant knowledge.

Continue to follow into the parent constructor:

Public DefaultChannelConfig (Channel channel) {this (channel, new AdaptiveRecvByteBufAllocator ());}

It's time to get to the familiar part, that is, both NioServerSocketChannel and NioSocketChannel will eventually initialize the DefaultChannelConfig and create a variable ByteBuf allocator, which we've discussed in detail in the previous section.

The above is all the contents of the article "how to create the Netty client access process NioSocketChannel". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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