netty 4.0.13 使用样例

来源:互联网 发布:天津网络推广公司排名 编辑:程序博客网 时间:2024/04/24 00:37
public boolean connect(final int port ,final String host, final NettyEntity entity) throws Exception {   Thread.sleep(5000);   EventLoopGroup workerGroup = new NioEventLoopGroup();   try {      Bootstrap b = new Bootstrap();      b.group(workerGroup);      b.channel(NioSocketChannel.class);      b.option(ChannelOption.SO_KEEPALIVE, true);      b.handler(new ChannelInitializer<SocketChannel>() {         @Override         protected void initChannel(SocketChannel ch) throws Exception {            ChannelPipeline pipeline = ch.pipeline();            pipeline.addLast("frameDecoder",new LengthFieldBasedFrameDecoder(1024*1024, 0,4, 0, 4));            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));            pipeline.addLast("decoder",new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));            pipeline.addLast("encoder",new ObjectEncoder());            pipeline.addLast("handler", new NettyClientCSHandler());         };      });      try {         byte[] entityBytes = CompressUtil.compress(JSON.toJSONString(entity).getBytes());         ChannelFuture  f = b.connect(host, port).sync();         f.channel().writeAndFlush(entityBytes);         f.channel().closeFuture().sync();         logger.info("执行JOB端:发送JOB到Server("+host+":"+port+")写数据完成,数据包大小:"+entityBytes.length );         return true;      }catch (Exception e){         logger.error("monitor error , 连接Server失败"+ host+":"+port+"{}");         return false;      }   } finally {      workerGroup.shutdownGracefully();   }}public class NettyClientCSHandler extends ChannelInboundHandlerAdapter  {   private static final Logger logger = LoggerFactory.getLogger(NettyClientCSHandler.class);   public NettyClientCSHandler(){   }   /**    *  NETTY 通信 CLIENT TO SERVER 回调接收    * @param ctx    * @param msg    * @throws Exception    */   @Override   public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {      try {         String result = new String(CompressUtil.uncompress((byte[]) msg));         if(!StringUtils.isEmpty(result)) {            Map backData = JSONUtil.jsonToMap(result);            if (backData != null) {               logger.error("✔  ****** Client接收到Server回调SUCCESS成功,DB数据处理成功 ******");            }         }else{            logger.error("✘  ****** Client接收到Server回调ERROR失败 ****:" + result);         }      }catch (Exception e){         logger.error("✘  ****** NETTY 通信 CLIENT TO SERVER 回调接收 ERROR失败 ****:",e);      }finally {         ctx.close();      }   }   @Override   public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {      logger.error("****** Netty Client报错 ******",cause.getMessage());   }

0 0
原创粉丝点击