前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Netty01--- Netty实现简单通信

Netty01--- Netty实现简单通信

作者头像
付威
发布2020-02-17 11:43:45
4190
发布2020-02-17 11:43:45
举报

这个Demo的功能是客户端向服务端发送一个Hello Netty的消息,然后服务端又把消息返回给客户端

Server端

这些都是一些公共的代码,代码比较简单,服务端负责监听端口,Handler负责处理业务逻辑

代码语言:javascript
复制
public class ServerProcessor {
     public void process(){
          EventLoopGroup bossGroup = new NioEventLoopGroup();
          EventLoopGroup workGroup = new NioEventLoopGroup();
          ServerBootstrap bootStrap = new ServerBootstrap();
          ChannelFuture cf;
          bootStrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         public void initChannel(SocketChannel ch) throws Exception {
                              ChannelPipeline p = ch.pipeline();
                              p.addLast(new ServerMessageHandler());//server的handler
                         }
                    });

          try {
               cf =  bootStrap.bind(8099).sync();//监听8099端口
               System.out.println("8099:binded...");
               cf.channel().closeFuture().sync();
          } catch (InterruptedException e) {
               e.printStackTrace();
          }finally{
               bossGroup.shutdownGracefully();
               workGroup.shutdownGracefully();
          }
     }

     public static void main(String[] args) {
          ServerProcessor serverProcessor = new ServerProcessor();
          serverProcessor.process();
     }
}
代码语言:javascript
复制
@ChannelHandler.Sharable
public class ServerMessageHandler extends ChannelInboundHandlerAdapter {

     @Override
     public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
          System.out.println("服务已启动,等待客户连接");
     }

     
     //接收客户端发送的消息
     @Override
     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
          ByteBuf in = (ByteBuf)msg;/*netty实现的缓冲区*/
          System.out.println("Server Accept:"+in.toString(CharsetUtil.UTF_8));
          ctx.write(in);
     }

     @Override
     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
          ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)/*flush掉所有的数据*/
                    .addListener(ChannelFutureListener.CLOSE);/*当flush完成后,关闭连接*/
     }
}

Client端

代码语言:javascript
复制
public class ClientProcessor {

     public void process() {
          EventLoopGroup group =new NioEventLoopGroup();
          try {
               Bootstrap b = new Bootstrap();
               b.group(group)
                         .channel(NioSocketChannel.class)
                         .option(ChannelOption.TCP_NODELAY, true)
                         .handler(new ChannelInitializer<SocketChannel>(){
                         @Override
                         public void initChannel(SocketChannel ch) throws Exception {
                              ChannelPipeline p = ch.pipeline();
                              p.addLast(new ClientMessageHandler());

                         }
                         });

               ChannelFuture future = b.connect("127.0.0.1", 8099).sync();//连接端口

               future.channel().closeFuture().sync();
          } catch (InterruptedException e) {
               e.printStackTrace();
          } finally {
               group.shutdownGracefully();
          }

     }

     public static void main(String[] args) {
          ClientProcessor clientProcessor = new ClientProcessor();
          clientProcessor.process();
     }
}
代码语言:javascript
复制
public class ClientMessageHandler extends SimpleChannelInboundHandler<ByteBuf> {

     @Override
     public void channelActive(ChannelHandlerContext ctx) throws Exception {
          ctx.channel().writeAndFlush(Unpooled.copiedBuffer("Hello Netty", CharsetUtil.UTF_8));
          ctx.fireChannelActive();
     }


     @Override
     protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
          System.out.println("NettyClient accetp:" + byteBuf.toString(CharsetUtil.UTF_8));
     }

     @Override
     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
          cause.printStackTrace();
          ctx.close();
     }

}

(本文完)

作者:付威 博客地址:http://blog.laofu.online 如有任何知识产权、版权问题或理论错误,还请指正。 本文是付威的网络博客原创,自由转载-非商用-非衍生-保持署名,请遵循:创意共享3.0许可证

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Server端
  • Client端
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档