netty 实现代理服务器群发

本文详细介绍如何使用Netty 4.1.30版本搭建一个简单的代理服务器,包括客户端、代理服务器及主服务器的实现代码。通过此教程,读者可以了解Netty在代理服务器场景中的应用,以及如何进行数据转发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于工作需要,最近要搞起 netty 呀~~,
搞了两天教程,今天突然看到可以做代理,心血来潮,决定写了,
找了找网上的一些教程,不知道是我代码有问题还是我智商问题,代码都跑不起来,还有就是觉得别人写的貌似有点问题(貌似我的问题也不少),
下面是自己 YY 的一些代码,如果有大神的话请多多指点,谢谢哇!

一、客户端

public class MyClient {
        
    public static void main(String[] args) throws Exception {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            Channel channel = b.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new MyClientChannelInitializer())
                .connect("localhost", 8080)//连接到代理服务器
                .channel();
            //接收用户输入,并发送给代理服务器
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                channel.writeAndFlush(reader.readLine() + "\n");
            }
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

}
public class MyClientChannelHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("客户端收到消息: " + msg);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
public class MyClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast(new LengthFieldPrepender(4));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast("用户" + new Random().nextInt(100) , new MyClientChannelHandler());
    }
}

二、代理服务器

public class MyProxyServer {
    
    public static void main(String[] args) throws Exception {
        EventLoopGroup parentGroup = new NioEventLoopGroup(1);
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(parentGroup, childGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new MyProxyChannelInitializer())
                .bind(new InetSocketAddress(8080))
                .sync()
                .channel()
                .closeFuture()
                .sync();
            } finally {
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }
    }

}
public class MyProxyChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //下面的解码和编码器很重要,不写的话数据转发不出去,因为数据在编码解码的过程中被丢弃了
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast(new LengthFieldPrepender(4));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new MyProxyChannelHandler());
    }

}
public class MyProxyChannelHandler extends ChannelInboundHandlerAdapter {
    
    // 这个 channel 是通向主服务器的
    private Channel channel;
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("代理服务器接收到【" + ctx.channel().remoteAddress() + "】的连接");
        //当一个客户端请求进来代理服务器的时候,代理服务器把这个请求连接到正真的服务器上
        Bootstrap b = new Bootstrap();
        channel = b.channel(ctx.channel().getClass())//和当前 channel 使用相同的 channelClass 类型
            .group(ctx.channel().eventLoop()) //和当前 channel 共用 eventLoop 以节省资源
            //这里一定要 ctx.channel(),因为这个 channel 是连接到客户端的,要往客户端发送数据的话需要用到这个 channel
            .handler(new MyClientProxyInitializer(ctx.channel()))
            .connect("localhost", 8090).channel();
    }
    
    @Override
    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        System.out.println("代理服务器开始转发【" + ctx.channel().remoteAddress() + "】的数据:" + msg);
        channel.writeAndFlush(msg);//把客户端发送上来的数据转发到主服务器上
    }
}
public class MyClientProxyInitializer extends ChannelInitializer<SocketChannel> {
    private Channel clientChannel;
    public MyClientProxyInitializer(Channel clientChannel) {
        this.clientChannel = clientChannel;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //下面的解码和编码器很重要,不写的话数据转发不出去,因为数据在编码解码的过程中被丢弃了
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast(new LengthFieldPrepender(4));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new MyClientProxyHandler(clientChannel));
    }

}
public class MyClientProxyHandler extends ChannelInboundHandlerAdapter {
 
    private Channel clientChannel;
    public MyClientProxyHandler(Channel clientChannel) {
        this.clientChannel = clientChannel;
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("开始转发消息【" + msg +"】给客户端");
        clientChannel.writeAndFlush(msg);//把主服务器发过来的数据转发回去客户端
    }
}

三、主服务器

public class MyServer {
    
    public static void main(String[] args) throws Exception {
        EventLoopGroup parentGroup = new NioEventLoopGroup(1);
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(parentGroup, childGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new MyChannelInitializer())
                .bind(new InetSocketAddress(8090))
                .sync();
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                MyChannelHandler.group.writeAndFlush(reader.readLine());
            }
        } finally {
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }
    }

}
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast(new LengthFieldPrepender(4));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new MyChannelHandler());
    }

}

public class MyChannelHandler extends ChannelInboundHandlerAdapter {
    
    public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        System.out.println("服务器接收到【" + ctx.channel().remoteAddress() + "】的消息:" + msg);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务器接收到【" + ctx.channel().remoteAddress() + "】的连接");
    }
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //把每个连接过来的客户端添加到 ChannelGroup 中,用于消息群发
        group.add(ctx.channel());
        super.handlerAdded(ctx);
    }
}

netty 版本:4.1.30
jdk:1.8
代码运行后可以通过客户端给服务器发送消息
可以多个客户端同时给服务器发送消息
服务器可以同时给所有客户端发送消息
代码地址:https://github.com/wongtp/test-netty

Netty是一款基于NIO的网络编程框架,提供了高效、稳定、灵活的网络编程能力。使用Netty实现代理服务器可以简化开发过程,提高性能和可维护性。 以下是使用Netty实现代理服务器的示例代码: ``` import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.stream.ChunkedWriteHandler; public class ProxyServer { public static void main(String[] args) throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup) .channel(NioSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .option(ChannelOption.AUTO_READ, false) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()); ch.pipeline().addLast(new HttpObjectAggregator(65536)); ch.pipeline().addLast(new ChunkedWriteHandler()); ch.pipeline().addLast(new ProxyServerHandler()); } }); ChannelFuture future = bootstrap.connect("www.example.com", 80).sync(); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); } } private static class ProxyServerHandler extends ChannelInboundHandlerAdapter { private Channel remoteChannel; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { remoteChannel = ctx.channel(); ctx.read(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; String host = request.headers().get("Host"); ChannelFuture future = new Bootstrap() .group(ctx.channel().eventLoop()) .channel(ctx.channel().getClass()) .handler(new LoggingHandler(LogLevel.INFO)) .option(ChannelOption.AUTO_READ, false) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpResponseDecoder()); ch.pipeline().addLast(new HttpObjectAggregator(65536)); ch.pipeline().addLast(new ChunkedWriteHandler()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(request); ctx.read(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; response.headers().remove("Transfer-Encoding"); response.headers().remove("Content-Length"); remoteChannel.writeAndFlush(response); remoteChannel.writeAndFlush(new ChunkedNioStream((ByteBuf) msg)); } else if (msg instanceof HttpContent) { remoteChannel.writeAndFlush(new ChunkedNioStream((ByteBuf) msg)); if (msg instanceof LastHttpContent) { remoteChannel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); } } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { remoteChannel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); remoteChannel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); } }); } }) .connect(host, 80); remoteChannel.config().setAutoRead(false); future.addListener((ChannelFutureListener) future1 -> { if (future1.isSuccess()) { remoteChannel.config().setAutoRead(true); ctx.channel().config().setAutoRead(true); } else { remoteChannel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); } }); } else if (msg instanceof HttpContent) { remoteChannel.writeAndFlush(new ChunkedNioStream((ByteBuf) msg)); if (msg instanceof LastHttpContent) { remoteChannel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (remoteChannel != null) { remoteChannel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); if (remoteChannel != null) { remoteChannel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) .addListener(ChannelFutureListener.CLOSE); } ctx.close(); } } } ``` 以上代码中,代理服务器连接到目标服务器的IP地址和端口号是硬编码的,你需要根据实际情况进行修改。在启动代理服务器之后,当客户端发送HTTP请求时,会在一个新的线程中处理请求,解析请求并连接到目标服务器,将请求转发给目标服务器。接收到目标服务器的响应后,将响应转发给客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值