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

Example Analysis of the method of registering Netty distributed NioSocketChannel to selector

2025-04-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shares with you the content of a sample analysis of Netty distributed NioSocketChannel registration to selector methods. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Let's go back to the original NioMessageUnsafe read () method:

Public void read () {/ / must be called by NioEventLoop method and cannot be called by external thread assert eventLoop () .inEventLoop (); / / config final ChannelConfig config of server channel = config (); / / pipeline final ChannelPipeline pipeline of server channel = pipeline (); / / rate of server access 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}

After the end of the while loop, the readBuf collection is traversed through a for loop, and the created NioSocketChannel is passed into fireChannelRead (), propagating the read event of the channel

The knowledge of pipeline will be analyzed in detail in the next chapter, and we will review the previous operations on pipeline based on the dissected content. here we just need to know that through fireChannelRead () we finally called the channelRead () method in ServerBootstrap's inner class ServerBootstrapAcceptor.

Follow to the channelRead () method:

Public void channelRead (ChannelHandlerContext ctx, Object msg) {final Channel child = (Channel) msg; / / Code omit try {/ / work thread registration channel childGroup.register (child) .addListener (new ChannelFutureListener () {@ Override public void operationComplete (ChannelFuture future) throws Exception {if (! future.isSuccess ()) {forceClose (child, future.cause ()) });} catch (Throwable t) {forceClose (child, t);}}

The msg of the parameter is the NioSocketChannel that was originally passed into the fireChannelRead () method.

So you can get the NioSocketChannel here by final Channel child = (Channel) msg

ChildGroup is the work thread we initially initialized. The register () method here, like the boss thread, selects a thread to register through the next () method. I will not repeat it here.

We follow the call chain to the register () method of SingleThreadEventLoop:

Public ChannelFuture register (final ChannelPromise promise) {ObjectUtil.checkNotNull (promise, "promise"); promise.channel (). Unsafe (). Register (this, promise); return promise;}

The unsafe () here, according to our previous analysis, is NioByteUnsafe, and the register here will eventually call the register () method of AbstractUnsafe and NioSocketChannel

I don't know if the students remember this method when they registered for NioServerSocketChannel.

Let's follow the register () method:

Public final void register (EventLoop eventLoop, final ChannelPromise promise) {/ / omit the verification code / / all replication operations are handed over to eventLoop to handle AbstractChannel.this.eventLoop = eventLoop; if (eventLoop.inEventLoop ()) {/ / do the actual master registration register0 (promise) } else {try {eventLoop.execute (new Runnable () {@ Override public void run () {register0 (promise);}});} catch (Throwable t) {/ / Code omission}

After we have learned the relevant knowledge of NioEventLoop, we should be familiar with this part of the code. We should first determine whether it is the current NioEventLoop thread. If so, register directly. If not, it will be encapsulated as task and executed in the current NioEventLoop.

It is not difficult to understand that this is not the current NioEventLoop thread, it is executed by the boss thread, so here we will go to else. If this is the first connection operation, the NioEventLoop of the work thread is not started, so here we will also start NioEventLoop and start the polling operation.

Follow register0 (promise) to see how it actually works:

Private void register0 (ChannelPromise promise) {try {/ / omit the code / / do the actual registration doRegister (); neverRegistered = false; registered = true; / / trigger event pipeline.invokeHandlerAddedIfNeeded (); safeSetSuccess (promise); / / trigger registration success event pipeline.fireChannelRegistered () If (isActive ()) {if (firstRegistration) {/ / propagate active events (4) pipeline.fireChannelActive ();} else if (config (). IsAutoRead ()) {beginRead ();} catch (Throwable t) {/ / omit code}}

This code is also familiar to us, because NioServerSokectChannel also takes this part, and we continue to focus on the doRegister () method:

Protected void doRegister () throws Exception {boolean selected = false; for (;;) {try {/ / jdk underlying registration method / / the first parameter is selector, and the second parameter indicates that you do not care about any event selectionKey = javaChannel (). Register (eventLoop (). Selector, 0, this); return } catch (CancelledKeyException e) {/ / omit code}

This part is also the underlying registration of jdk that we have analyzed before, except that the javaChannel () here is SocketChanel rather than ServerSocketChannel.

Similarly, it also means that you don't care about any events, but just register on the selector bound by the current NioEventLoop.

Thank you for reading! This is the end of this article on "example analysis of Netty distributed NioSocketChannel registration to selector method". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

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