zoukankan      html  css  js  c++  java
  • nettyclient异步获取数据

    源代码见,以下主要是做个重要代码记录

    http://download.csdn.net/detail/json20080301/8180351


    NETTYclient获取数据採用的方式是异步获取数据,不像socket你不知道服务端何时处理请求,何时能得到响应。即使得到响应也没法自己主动退出程序。

    必须使用下面步骤:


    =================step 0.当然是发起异步连接操作,等待client链路关闭

    //发起异步连接操作
    ChannelFuture f = b.connect(this.host, this.port).sync();
    //等待client链路关闭
    f.channel().closeFuture().sync();


    ================step1.加入超时handler : pipeline.addLast( new ReadTimeoutHandler(6));


    ================step2.//优雅退出,释放NIO线程组 group.shutdownGracefully();


    ================step3.自己定义EchoClientHandler ,捕获ReadTimeoutHandler的6秒异常,然后关闭链路

    public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    /* 
    *捕获ReadTimeoutHandler的6秒异常,然后关闭链路。 
    */
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    logger.log(Level.WARNING, "Unexpected exception from downstream.",
    cause);
    ctx.close();//发生异常关闭链路
    }

    }


    ====================对于第三步我想说,假设你自己定义的数据协议中有推断消息包是否结束的方法。也能够将 ctx.close();//发生异常关闭链路 , 举比例如以下:

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
    if(sureQuit()){
    // ctx.close();
    }
    }

    推断能否够关闭链路;一旦关系链路,client代码就会运行 group.shutdownGracefully(); 释放线程组,这样client就能够整个进程退出啦。

     

  • 相关阅读:
    获取时间对象
    定时器
    undefined与return
    获取设置非行间样式
    NaN
    return,break与continue的区别
    数据类型
    程序的机器级表示
    计算机内数字的表示
    计算机系统漫游
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5057933.html
Copyright © 2011-2022 走看看