栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

netty服务器和客户端

netty服务器和客户端

服务器
public class HelloServer {
    public static void main(String[] args) {
        // 1 启动器负责组装netty组件,启动服务器
        new ServerBootstrap()
                // 2 group组 线程和选择器
               .group(new NioEventLoopGroup())
                // 选择实现 nio oio bio  epoll
                // 3 选择服务器的 ServerSocketChannel 实现
               .channel(NioServerSocketChannel.class)
                // 4 负责处理连接 负责处理读写 决定了worker能处理哪些操作
               .childHandler(
                       // 代表和客户端进行数据读写的通道,负责添加别的handler
                       new ChannelInitializer() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                // 6 添加具体handler
                                ch.pipeline().addLast(new StringDecoder()); //将byteBuffer转换为字符串
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){ // 自定义handler

                                // 读事件
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    // 打印上一步转换好的字符串
                                    System.out.println(msg);
                                }
                       });
                   }
               })
                // 绑定监听端口
                .bind(8888);
    }
}
客户端
public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        // 启动类
        new Bootstrap()
                // 添加事件循环
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                // 初始化器,在连接建立后会调用
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost",8888))
                .sync()
                .channel()
                .writeAndFlush("hello,jhh");
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/742937.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号