netty实现最基本的双向通信

  • Post author:
  • Post category:其他

刚学习了一下netty,但是不成系统,东看看西看看,所以写了一个demo实现一下最基本的客户端服务端通信,这肯定是最基本的实现了,适合新手理解。

客户端:

public class OchatServer {

    private static HashMap<ChannelHandlerContext, String> ctxMap = new HashMap<>();

    private static int num = 0;

    public static void main(String[] args) throws InterruptedException {

        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        onInitChannel(ch);
                    }
                })
                .bind("127.0.0.1", 8080);

        System.out.println("请输入内容:(格式:客户号.内容)");
        while (true) {
            Thread.sleep(10);
            if (!ctxMap.isEmpty()) {
                Scanner scanner = new Scanner(System.in);
                String s = scanner.nextLine();
                String[] split = s.split("-");
                ChannelHandlerContext ctx = findCtx(split[0]+ "号客户");

                ctx.channel().writeAndFlush(split[1]);
            }
        }


    }

    private static ChannelHandlerContext findCtx(String value) {
//        System.out.println(value);
        Iterator<Map.Entry<ChannelHandlerContext, String>> iterator = ctxMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<ChannelHandlerContext, String> next = iterator.next();
            if (value.equals(next.getValue())) {
                return next.getKey();
            }
        }
        return null;
    }

    private static void onInitChannel(NioSocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new StringEncoder());
        p.addLast(new StringDecoder());
        p.addLast(new MyServerHandler());
    }

    private static class MyServerHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            ctxMap.put(ctx, (++num) + "号客户");
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(ctxMap.get(ctx) + "已登录");
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println(ctxMap.get(ctx) + ": " + msg);
        }
    }


}

服务端

public class OchatCilent {
    public static void main(String[] args) {

        Bootstrap bootstrap = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .remoteAddress("127.0.0.1", 8080)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        onInitChannel(ch);
                    }
                });

        Channel channel = bootstrap.connect().channel();

        System.out.println("请输入:");
        while (true) {
            Scanner scanner = new Scanner(System.in);
            channel.writeAndFlush(scanner.nextLine());
        }


    }


    private static void onInitChannel(NioSocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new StringEncoder());
        p.addLast(new StringDecoder());
        p.addLast(new MyClientHandler(ch));
    }

    private static class MyClientHandler extends ChannelInboundHandlerAdapter {

        private NioSocketChannel nioSocketChannel;

        public MyClientHandler(NioSocketChannel nioSocketChannel) {
            this.nioSocketChannel = nioSocketChannel;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("server say :" + msg);
        }
    }

}

实现效果:两个客户端时


版权声明:本文为weixin_48515459原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。