溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

proxy代理示例分析

發(fā)布時(shí)間:2021-12-17 14:42:36 來源:億速云 閱讀:203 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要講解了“proxy代理示例分析”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“proxy代理示例分析”吧!

準(zhǔn)備工作:

將代碼全部整理clone到本地,IDE可以正常打開即可。 后邊的分析也都一樣。

proxy代理示例分析

核心分析

proxy的位置

proxy代理示例分析

框架圖

此示例主要是進(jìn)行的代理訪問的數(shù)據(jù)轉(zhuǎn)發(fā)。

proxy代理示例分析

  • 請(qǐng)求-》LocalServer=》RemoteServer

  • RemoteServer 返回?cái)?shù)據(jù)=>LocalServer=>客戶接收

代碼分析
HexDumpProxy 主邏輯

代碼預(yù)覽:

proxy代理示例分析

我把原來代碼中端口和域名修改了下,不影響觀看

代碼解讀

        //準(zhǔn)備好兩個(gè)EventLoop,一個(gè)是為連接使用, 一個(gè)是為讀寫具體數(shù)據(jù)準(zhǔn)備
        EventLoopGroup bossGroup = new NioEventLoopGroup(1); 
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) //管道類型 NioServerSocketChannel 裝配管道類型 ,可以先不看
             .handler(new LoggingHandler(LogLevel.INFO)) //(可選)此處是額外增加了一個(gè)日志打印,觀看數(shù)據(jù)是否準(zhǔn)確。
             .childHandler(new HexDumpProxyInitializer(REMOTE_HOST, REMOTE_PORT))// (關(guān)鍵 1) 設(shè)置Child的Handler處理類
             .childOption(ChannelOption.AUTO_READ, false) //(關(guān)鍵 2)設(shè)置自動(dòng)讀取為false
             .bind(LOCAL_PORT).sync().channel().closeFuture().sync(); //啟動(dòng)服務(wù)
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
  • 關(guān)鍵 1

HexDumpProxyInitializer 是接下來的數(shù)據(jù)讀取處理Initializer初始化對(duì)象

  • 關(guān)鍵 2

ChannelOption.AUTO_READ 將管道自動(dòng)讀設(shè)置成關(guān)閉,讓程序后面邏輯去控制

  • LoggingHandler 日志打印

不是必要的,是為了調(diào)試看方便使用 如圖 proxy代理示例分析

接著看 HexDumpProxyInitializer 邏輯
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<SocketChannel> {//繼承  ChannelInitializer<SocketChannel>

    private final String remoteHost;
    private final int remotePort;

    public HexDumpProxyInitializer(String remoteHost, int remotePort) {   //(關(guān)鍵 1) 將遠(yuǎn)端的地址和端口傳入進(jìn)來
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
    }

    @Override
    public void initChannel(SocketChannel ch) {   //(關(guān)鍵 2) 覆蓋ChannelInitializer<SocketChannel>中的initChannel方法自定義初始化管道要做的事情
        ch.pipeline().addLast(
                new LoggingHandler(LogLevel.INFO),//增加日志
                new HexDumpProxyFrontendHandler(remoteHost, remotePort)); // (關(guān)鍵3)增加一個(gè)HexDumpProxyFrontendHandler處理器
    }
}
  • 關(guān)鍵 1

將遠(yuǎn)端的地址和端口傳入進(jìn)來,供后面使用

  • 關(guān)鍵 2

覆蓋initChannel ,自定義初始化管道要做的內(nèi)容

  • 關(guān)鍵 3

增加一個(gè)處理器 HexDumpProxyFrontendHandler

接著看 HexDumpProxyFrontendHandler 邏輯
public class HexDumpProxyFrontendHandler extends ChannelInboundHandlerAdapter {   //(關(guān)鍵1) 繼承ChannelInboundHandlerAdapter 輸入適配器

    private final String remoteHost;
    private final int remotePort;
 
    private Channel outboundChannel;// 聲明一個(gè)輸出管道

    public HexDumpProxyFrontendHandler(String remoteHost, int remotePort) {
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) { //(關(guān)鍵2)覆蓋管道激活時(shí)候觸發(fā)內(nèi)容
        final Channel inboundChannel = ctx.channel(); //獲取輸入管道

        //進(jìn)行裝配,如果管道激活,說明有請(qǐng)求來了,去請(qǐng)求后端
        Bootstrap b = new Bootstrap();
        b.group(inboundChannel.eventLoop())//設(shè)置和inboundChannel同樣的EventLoop
         .channel(ctx.channel().getClass()) //設(shè)置和inboundChannel同樣的Channel
         .handler(new HexDumpProxyBackendHandler(inboundChannel))//(關(guān)鍵 3) 新建一個(gè)HexDumpProxyBackendHandler 將輸入管道傳進(jìn)去
         .option(ChannelOption.AUTO_READ, false);//也是同樣關(guān)閉
        ChannelFuture f = b.connect(remoteHost, remotePort); //去連接遠(yuǎn)程remoteHost
        outboundChannel = f.channel();//獲取與遠(yuǎn)程服務(wù)器建立的管道
        f.addListener(new ChannelFutureListener() {// 增加一個(gè)監(jiān)聽當(dāng)數(shù)據(jù)完成時(shí)候出發(fā)管道的狀態(tài)
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {//如果管道建立成功就讓輸入管道等待讀取客戶傳來的信息
                    // connection complete start to read first data
                    inboundChannel.read();
                } else {
                    // Close the connection if the connection attempt has failed.
                    inboundChannel.close();//如果失敗那就關(guān)閉輸入流
                }
            }
        });
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) { //輸入管道可以讀取時(shí)候
        if (outboundChannel.isActive()) { //查看遠(yuǎn)端管道是否為激活狀態(tài)
            outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {  //(關(guān)鍵 4)將數(shù)據(jù)轉(zhuǎn)發(fā)寫入到outboundChannel的管道里面
                @Override
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) {
                        // 如果轉(zhuǎn)發(fā)完成,繼續(xù)讀取
                        ctx.channel().read(); 
                    } else {
                        future.channel().close();//否則關(guān)閉
                    }
                }
            });
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) { //如果輸入管道關(guān)閉,且遠(yuǎn)程管道也沒有關(guān)閉的情況,進(jìn)行刷新關(guān)閉。
        if (outboundChannel != null) {
            closeOnFlush(outboundChannel);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { //如果異常時(shí)候也進(jìn)行刷新關(guān)閉
        cause.printStackTrace();
        closeOnFlush(ctx.channel());
    }

    /**
     * 靜態(tài)方法,主動(dòng)刷新管道數(shù)據(jù)關(guān)閉管道
     */
    static void closeOnFlush(Channel ch) {
        if (ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }
}
  • 關(guān)鍵 1

繼承ChannelInboundHandlerAdapter 輸入適配器 可以選配覆蓋里面的很多方法,自由度很高,想處理激活狀態(tài)或者其他狀態(tài)覆蓋即可自定義了

  • 關(guān)鍵 2

管道激活時(shí)候觸發(fā)內(nèi)容,在此時(shí)建立遠(yuǎn)端連接,準(zhǔn)備好遠(yuǎn)端管道

  • 關(guān)鍵 3

新建一個(gè)HexDumpProxyBackendHandler 將當(dāng)前輸入管道傳進(jìn)去

  • 關(guān)鍵 4 (核心)

將數(shù)據(jù)轉(zhuǎn)發(fā)寫入到outboundChannel的管道里面,這是將客戶過來的數(shù)據(jù)寫入到遠(yuǎn)程管道里面

proxy代理示例分析

接著看 HexDumpProxyBackendHandler 邏輯
public class HexDumpProxyBackendHandler extends ChannelInboundHandlerAdapter {  // 同樣繼承ChannelInboundHandlerAdapter 輸入適配器

    private final Channel inboundChannel; //(關(guān)鍵 1) 保存?zhèn)魅氲妮斎牍艿?

    public HexDumpProxyBackendHandler(Channel inboundChannel) {
        this.inboundChannel = inboundChannel;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) { //如果管道被激活,發(fā)起讀請(qǐng)求等待
        ctx.read();
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) { 
        inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { //(關(guān)鍵2 )當(dāng)遠(yuǎn)端管道數(shù)據(jù)準(zhǔn)備好,就可以轉(zhuǎn)發(fā)到輸入管道中
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read(); //繼續(xù)讀請(qǐng)求
                } else {
                    future.channel().close();//如果不成功關(guān)閉管道
                }
            }
        });
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        HexDumpProxyFrontendHandler.closeOnFlush(inboundChannel); //如果遠(yuǎn)端流管道失效,調(diào)用HexDumpProxyFrontendHandler的closeOnFlush關(guān)閉輸入管道,靜態(tài)方法可以直接調(diào)用
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {  //如果異常,也同樣調(diào)用HexDumpProxyFrontendHandler的closeOnFlush關(guān)閉輸入管道
        cause.printStackTrace();
        HexDumpProxyFrontendHandler.closeOnFlush(ctx.channel());
    }
}
  • 關(guān)鍵 1 保存?zhèn)魅氲妮斎牍艿?/p>

  • 關(guān)鍵 2 (核心) 當(dāng)遠(yuǎn)端管道數(shù)據(jù)準(zhǔn)備好,就可以轉(zhuǎn)發(fā)到輸入管道中 proxy代理示例分析

感謝各位的閱讀,以上就是“proxy代理示例分析”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)proxy代理示例分析這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI