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

Sample Analysis of proxy Agent

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains the "proxy agent example analysis", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "proxy agent example analysis" bar!

Preparatory work:

Organize all the code clone to the local, IDE can be opened normally. The later analysis is the same.

Core analysis of the location of proxy

Frame diagram

This example is mainly about data forwarding for proxy access.

Request-"LocalServer=" RemoteServer

RemoteServer returns data = > LocalServer= > customer receives

Code analysis HexDumpProxy main logic

Code Preview:

I modified the port and domain name in the original code so that the viewing will not be affected.

Code interpretation

/ / prepare two EventLoop, one for connection and one for reading and writing specific data: EventLoopGroup bossGroup = new NioEventLoopGroup (1); EventLoopGroup workerGroup = new NioEventLoopGroup (); try {ServerBootstrap b = new ServerBootstrap () B.group (bossGroup, workerGroup) .channel (NioServerSocketChannel.class) / / Pipe type NioServerSocketChannel assembly pipe type, you can not look at the .handler (new LoggingHandler (LogLevel.INFO)) / / (optional) here is an additional log print to see if the data is accurate. .childHandler (new HexDumpProxyInitializer (REMOTE_HOST, REMOTE_PORT)) / / (key 1) set the Handler processing class of Child. ChildOption (ChannelOption.AUTO_READ, false) / / (key 2) set to read automatically to false. Bind (LOCAL_PORT). Sync (). Channel (). CloseFuture (). Sync (); / start the service} finally {bossGroup.shutdownGracefully () WorkerGroup.shutdownGracefully ();}

Key 1

HexDumpProxyInitializer is the next data read processing Initializer initialization object

Key 2

ChannelOption.AUTO_READ sets the automatic read of the pipe to be turned off, which is controlled by the logic behind the program.

LoggingHandler log printing

It's not necessary, it's for debugging, it's easy to use as shown in the picture.

Then look at the HexDumpProxyInitializer logic import io.netty.channel.ChannelInitializer;import io.netty.channel.socket.SocketChannel;import io.netty.handler.logging.LogLevel;import io.netty.handler.logging.LoggingHandler;public class HexDumpProxyInitializer extends ChannelInitializer {/ / inherit ChannelInitializer private final String remoteHost; private final int remotePort; public HexDumpProxyInitializer (String remoteHost, int remotePort) {/ / (key 1) pass in the remote address and port this.remoteHost = remoteHost; this.remotePort = remotePort } @ Override public void initChannel (SocketChannel ch) {/ / (key 2) override the initChannel method in ChannelInitializer to customize what the initialization pipeline does ch.pipeline () .addLast (new LoggingHandler (LogLevel.INFO), / / add log new HexDumpProxyFrontendHandler (remoteHost, remotePort)); / / (key 3) add a HexDumpProxyFrontendHandler processor}}

Key 1

Pass in the remote address and port for later use

Key 2

Override initChannel and customize what the pipeline needs to do.

Key 3

Add a processor HexDumpProxyFrontendHandler

Then look at the HexDumpProxyFrontendHandler logic public class HexDumpProxyFrontendHandler extends ChannelInboundHandlerAdapter {/ / (key 1) inherit ChannelInboundHandlerAdapter input adapter private final String remoteHost; private final int remotePort; private Channel outboundChannel;// declare an output pipeline public HexDumpProxyFrontendHandler (String remoteHost, int remotePort) {this.remoteHost = remoteHost; this.remotePort = remotePort } @ Override public void channelActive (ChannelHandlerContext ctx) {/ / (key 2) trigger content final Channel inboundChannel = ctx.channel () when the pipeline is activated; / / get the input pipeline / / assemble it. If the pipeline is activated, it means that a request is coming. Request the backend Bootstrap b = new Bootstrap (). B.group (inboundChannel.eventLoop ()) / / sets the same EventLoop channel (ctx.channel (). GetClass ()) / sets the same Channel as inboundChannel. Handler (new HexDumpProxyBackendHandler (inboundChannel)) / / (key 3) create a new HexDumpProxyBackendHandler to pass in the input pipe .option (ChannelOption.AUTO_READ, false); / / also close ChannelFuture f = b.connect (remoteHost, remotePort) / / to connect to the remote remoteHost outboundChannel = f.channel () / / get the f.addListener established with the remote server (new ChannelFutureListener () {/ / add a monitor. When the data is complete, the status of the originating pipeline @ Override public void operationComplete (ChannelFuture future) {if (future.isSuccess ()) {/ / if the pipeline is established successfully, let the input pipeline wait for the information sent by the customer to be read. / / connection complete start to read first data inboundChannel.read () } else {/ / Close the connection if the connection attempt has failed. InboundChannel.close (); / / close the input stream if it fails}) } @ Override public void channelRead (final ChannelHandlerContext ctx Object msg) {/ / when the input pipe can be read, if (outboundChannel.isActive ()) {/ / check whether the remote pipe is active outboundChannel.writeAndFlush (msg) .addListener (new ChannelFutureListener () {/ / (key 4)) forward and write data to outboundChannel's pipe @ Override public void operationComplete (ChannelFuture future) { If (future.isSuccess ()) {/ / if forwarding is complete Continue to read ctx.channel (). Read () } else {future.channel () .close (); / / otherwise close});} @ Override public void channelInactive (ChannelHandlerContext ctx) {/ / if the input pipe is closed and the remote pipe is not closed, refresh the shutdown. If (outboundChannel! = null) {closeOnFlush (outboundChannel);}} @ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {/ / disable cause.printStackTrace (); closeOnFlush (ctx.channel ()) if there is an exception } / * static method, actively refresh the pipeline data and close the pipeline * / static void closeOnFlush (Channel ch) {if (ch.isActive ()) {ch.writeAndFlush (Unpooled.EMPTY_BUFFER) .addListener (ChannelFutureListener.CLOSE);}

Key 1

Inherit ChannelInboundHandlerAdapter input adapter can choose to override many methods, high degree of freedom, want to deal with the active state or other state coverage can be customized

Key 2

Trigger the content when the pipe is activated, establish a remote connection at this time, and prepare the remote pipe.

Key 3

Create a new HexDumpProxyBackendHandler to transfer the current input pipeline

Key 4 (Core)

Write the data forward to the outboundChannel pipeline, which is to write the data from the customer to the remote pipeline.

Then look at the HexDumpProxyBackendHandler logic public class HexDumpProxyBackendHandler extends ChannelInboundHandlerAdapter {/ / also inherit the ChannelInboundHandlerAdapter input adapter private final Channel inboundChannel; / / (key 1) save the incoming input pipeline public HexDumpProxyBackendHandler (Channel inboundChannel) {this.inboundChannel = inboundChannel;} @ Override public void channelActive (ChannelHandlerContext ctx) {/ / if the pipe is activated, initiate a read request and wait for ctx.read () } @ Override public void channelRead (final ChannelHandlerContext ctx, Object msg) {inboundChannel.writeAndFlush (msg) .addListener (new ChannelFutureListener () {/ / (key 2)) when the remote pipeline data is ready, it can be forwarded to @ Override public void operationComplete (ChannelFuture future) {if (future.isSuccess ()) {ctx.channel (). Read () / / continue to read the request} else {future.channel () .close (); / / if the pipe is not successfully closed});} @ Override public void channelInactive (ChannelHandlerContext ctx) {HexDumpProxyFrontendHandler.closeOnFlush (inboundChannel) / / if the remote stream pipeline fails, call closeOnFlush of HexDumpProxyFrontendHandler to close the input pipeline. The static method can directly call} @ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {/ / if there is an exception, also call closeOnFlush of HexDumpProxyFrontendHandler to close the input pipeline cause.printStackTrace (); HexDumpProxyFrontendHandler.closeOnFlush (ctx.channel ());}}

Key 1 Save the incoming input pipe

Key 2 (core) when the remote pipeline data is ready, it can be forwarded to the input pipeline

Thank you for your reading, the above is the content of "proxy Agent sample Analysis", after the study of this article, I believe you have a deeper understanding of the proxy agent example analysis of this problem, the specific use also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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

Internet Technology

Wechat

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

12
Report