前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Netty|02 easy example

Netty|02 easy example

作者头像
微笑的小小刀
发布2019-09-10 15:10:21
4380
发布2019-09-10 15:10:21
举报
文章被收录于专栏:java技术大本营java技术大本营

入门案例

1、博主使用的IDE是idea,很强大的开发工具 2、为了精简篇幅,博主把代码中需要导入包那一块去除了,大家在操作的时候需要手动导包 3、入门案例的每一行代码都有对应的注释,便于大家理解

1、新建maven项目并且导入Netty的对应坐标

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.15.Final</version>
        </dependency>

2、新建NettyServer

public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
//        创建线程池 接受连接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
//        创建线程池,处理io
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
//        创建服务器端启动助手
        ServerBootstrap serverBootstrap = new ServerBootstrap();
//        配置启动助手
        serverBootstrap.group(bossGroup, workGroup)//设置两个线程池
                .channel(NioServerSocketChannel.class)//使用作为服务器端的通道实现
                .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列中等待连接的个数
                .childOption(ChannelOption.SO_KEEPALIVE, true)//保持活动连接状态
                .childHandler(new ChannelInitializer<SocketChannel>() { //创建通道初始化的对象
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyServerHandler());
                    }
                });
        System.out.println("----------------server is ready--------------------");
        ChannelFuture cf = serverBootstrap.bind(9999).sync();//绑定端口,异步
        System.out.println("----------------server is starting--------------------");
//        关闭通道、关闭通道组
        cf.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();

    }
}

3、新建服务器业务处理块NettyServerHandler

/**
 * 服务器业务处理块
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取数据事件
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server:"+ctx);
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("客户端发来消息:"+buf.toString(CharsetUtil.UTF_8));

    }

    /**
     *数据读取完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("就是没钱啦!",CharsetUtil.UTF_8));
    }

    /**
     * 异常发生
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

4、新建客户端NettyClient

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

//        创建一个线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        //2. 创建客户端的启动助手,完成相关配置
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)//3. 设置线程组
                .channel(NioSocketChannel.class)//4. 设置客户端通道的实现类
                .handler(new ChannelInitializer<SocketChannel>() {//5. 创建一个通道初始化对象
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyClientHandler());//6.往Pipeline链中添加自定义的handler
                    }
                });
        System.out.println("......Client is  ready......");

        //7.启动客户端去连接服务器端  connect方法是异步的   sync方法是同步阻塞的
        ChannelFuture cf = bootstrap.connect("127.0.0.1", 9999).sync();

//        关闭连接
        cf.channel().closeFuture().sync();

    }
}

5、新建客户端业务处理NettyClientHandler

public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 通道就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client:"+ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("老板还钱吧!", CharsetUtil.UTF_8));
    }

    /**
     * 读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("服务器发来消息:"+buf.toString(CharsetUtil.UTF_8));
    }
}

6、运行结果:

服务器端 ----------------server is ready-------------------- ----------------server is starting-------------------- server:ChannelHandlerContext(NettyServerHandler#0, [id: 0xa80ee519, L:/127.0.0.1:9999 - R:/127.0.0.1:60798]) 客户端发来消息:老板还钱吧! 客户端: ......Client is ready...... client:ChannelHandlerContext(NettyClientHandler#0, [id: 0xe77a3b4a, L:/127.0.0.1:60798 - R:/127.0.0.1:9999]) 服务器发来消息:就是没钱啦!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-09-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 java技术大本营 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、新建maven项目并且导入Netty的对应坐标
  • 2、新建NettyServer
  • 3、新建服务器业务处理块NettyServerHandler
  • 4、新建客户端NettyClient
  • 5、新建客户端业务处理NettyClientHandler
  • 6、运行结果:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档