netty 实现代理服务器群发

由于工作需要,最近要搞起 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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值