netty基础教程-3、helloworld(cs模式)

功能实现

服务端

  1. 接受客户端数据
  2. 响应结果给客户端

客户端

  1. 发送请求给服务端
  2. 接受服务端的响应

服务端实现

启动类:Server.java

public class Server {
    public static void main(String[] args) throws Exception{
        //创建两个组,分别用来接受客户端情求和处理客户端消息的
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        //配置服务端
        ChannelFuture cf = b.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
                //1)
                .childHandler(new ServerChannelInit())
                .bind(8899)
                .sync();
        System.out.println("服务端初始化完成!!!");
        //最后关闭服务端资源
        cf.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
        System.out.println("服务端停止服务!!!");
    }
}

1)、在这里将业逻辑注入,这样就很好的将业务和IO操作分离开了

通道初始化类:ServerChannelInit.java

public class ServerChannelInit extends ChannelInitializer<NioSocketChannel> {
    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        //对服务端管道进行配置,编解码,Handler的处理顺序等等
        ch.pipeline().addLast(new ServerHandler());
    }
}

通道数据处理类:ServerHandler.java

public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            //转换数据
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            System.out.println("接受到数据是:" + new String(bytes, "UTF-8"));
            //返回响应
            ByteBuf resp = Unpooled.copiedBuffer("服务端已经接受数据!!", CharsetUtil.UTF_8);
            ctx.writeAndFlush(resp);
        }finally {
            //释放
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("=============test通道激活============");
        super.channelActive(ctx);
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("=============test通道激活ing============");
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("=============test通道数据读取完毕!!============");
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("=============test通道激活出现异常============");
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}

客户端实现

启动类:Client.java

public class Client {
    public static void main(String[] args) throws Exception{
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        ChannelFuture cf = b.group(workGroup)
                .channel(NioSocketChannel.class)
                .handler(new ClientChannelInit())
                .connect("127.0.0.1", 8899)
                .sync();
        cf.channel().writeAndFlush(Unpooled.copiedBuffer("hello server",CharsetUtil.UTF_8));
        System.out.println("客户端初始化完成!!!!");
        cf.channel().closeFuture().sync();
    }
}

通道初始化类:ClientChannelInit.java

public class ClientChannelInit extends ChannelInitializer<NioSocketChannel> {
    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        ch.pipeline().addLast(new ClientHandler());
    }
}

通道数据处理类:ClientHandler.java

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            ByteBuf byteBuf = (ByteBuf)msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            System.out.println("接受到服务端的消息:"+new String(bytes,"UTF-8"));
        }finally {
            ReferenceCountUtil.release(msg);
        }

    }
}

总结

这里的操作有的还是很冗余的;强转数据,关闭ByteBuf等

github源码: https://github.com/wcjwctwy/netty-study

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值