源代碼見,以下主要是做個重要代碼記錄
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就能夠整個進程退出啦。
