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

时间:2019-02-03作者:klpeng分类:IT综合浏览:12366评论:0

功能实现

服务端

  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

打赏
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
相关推荐

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

猜你喜欢