zoukankan      html  css  js  c++  java
  • Java : Netty 入门案例

    接收端代码:

    public class IOServer {
        public static void main(String[] args) throws IOException, InterruptedException {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            NioEventLoopGroup boos = new NioEventLoopGroup();
            NioEventLoopGroup worker = new NioEventLoopGroup();
            serverBootstrap
                    .group(boos, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        protected void initChannel(NioSocketChannel ch) {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                    System.out.println(msg);
                                }
                            });
                        }
                    })
                    .bind(9990);
        }
    }

    发送端代码:

    public class IOClient {
        public static void main(String[] args) throws InterruptedException {
            Bootstrap bootstrap = new Bootstrap();
            NioEventLoopGroup group = new NioEventLoopGroup();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder());
                        }
                    });
            Channel channel = bootstrap.connect("127.0.0.1", 9999).channel();
            while (true) {
                channel.writeAndFlush(new Date() + "hello world");
                Thread.sleep(2000);
            }
        }
    }

    此案例基于netty4, 并且推荐使用netty4进行开发, netty5分支已经被作者remove, 原因: https://github.com/netty/netty/issues/4466

    netty4用 ChannelInboundHandlerAdapter 和 ChannelOutboundHandlerAdapter 来区分上行(接收)和下行(发送)的数据, 而 netty5中这两个类均已经被废弃

  • 相关阅读:
    libevent学习总结
    C#结构体的使用
    函数常用类
    C#函数的基础应用
    数组的应用:冒泡排序,折半查找及二维数组的应用
    作业
    复习break、continue、while、do-while的运用
    编程常用英语单词
    作业:for循环,迭代法和穷举法
    循环语句
  • 原文地址:https://www.cnblogs.com/cccy0/p/10563800.html
Copyright © 2011-2022 走看看