netty 处理远程主机强制关闭一个连接,首先看下api解释:
/**
*Returns{@codetrue}ifandonlyifthechannelshouldnotcloseitselfwhenitsremote
*peershutsdownoutputtomaketheconnectionhalf-closed.If{@codefalse},theconnection
*isclosedautomaticallywhentheremotepeershutsdownoutput.
*/
booleanisAllowHalfClosure();
/**
*Setswhetherthechannelshouldnotcloseitselfwhenitsremotepeershutsdownoutputto
*maketheconnectionhalf-closed.If{@codetrue}theconnectionisnotclosedwhenthe
*remotepeershutsdownoutput.Instead,
*{@linkChannelInboundHandler#userEventTriggered(ChannelHandlerContext,Object)}
*isinvokedwitha{@linkChannelInputShutdownEvent}object.If{@codefalse},theconnection
*isclosedautomatically.
*/
SocketChannelConfigsetAllowHalfClosure(booleanallowHalfClosure);
默认是自动关闭channel,但是这样无法捕获远程主机强制关闭一个连接异常,所以 设置serverconfig
allowHalfClosure=true
这里初始化配置可以在下面的方法中处理
/**
*Thismethodwillbecalledoncethe{@linkChannel}wasregistered.Afterthemethodreturnsthisinstance
*willberemovedfromthe{@linkChannelPipeline}ofthe{@linkChannel}.
*
*@paramchthe{@linkChannel}whichwasregistered.
*@throwsExceptionisthrownifanerroroccurs.Inthatcaseitwillbehandledby
*{@link#exceptionCaught(ChannelHandlerContext,Throwable)}whichwillbydefaultclose
*the{@linkChannel}.
*/
protectedabstractvoidinitChannel(Channelch)throwsException;
像这样:
ch.config().setAllowHalfClosure(true);
就可以在
/**
*Calls{@linkChannelHandlerContext#fireUserEventTriggered(Object)}toforward
*tothenext{@linkChannelInboundHandler}inthe{@linkChannelPipeline}.
*
*Sub-classesmayoverridethismethodtochangebehavior.
*/
@Override
publicvoiduserEventTriggered(ChannelHandlerContextctx,Objectevt)throwsException{
ctx.fireUserEventTriggered(evt);
}
中捕获远程主机强制关闭一个连接了 想这样处理,在自己的handler中重写上面的方法:
/**
*读取数据超时--->断定连接断开---->释放对应的socket连接
*
*心跳处理
*链路读写超时处理
*
*@paramctx
*@paramevt
*@throwsExceptionsub_reactorChannelInputShutdownEvent.INSTANCE
*/
@Override
publicvoiduserEventTriggered(ChannelHandlerContextctx,Objectevt)throwsException{
try{
Channelchannel=ctx.channel();
if(evtinstanceofIdleStateEvent){
IdleStateEvente=(IdleStateEvent)evt;
if(e.state()==IdleState.READER_IDLE){
channel.close();//callbackchannelInactive(ChannelHandlerContextctx)
if(logger.isDebugEnabled())logger
.debug(channel.remoteAddress()+"---Nodatawasreceivedforawhile,readtimeout......");
}//becauseweareattachingmoreimportancetotheread_idletime(timeouttorec)
elseif(e.state()==IdleState.WRITER_IDLE){//Nodatawassentforawhile.
channel.close();
if(logger.isDebugEnabled())logger
.debug(channel.remoteAddress()+"---Nodatawassentforawhile.writetimeout......");
}
}elseif(evtinstanceofChannelInputShutdownEvent){
channel.close();//远程主机强制关闭连接
}
}catch(Exceptione){
e.printStackTrace();
}
}
通过以上设置就可以捕获 并处理逻辑相关资源了netty 处理远程主机强制关闭一个连接
如果觉得《java nio 强制关闭_netty 处理远程主机强制关闭一个连接》对你有帮助,请点赞、收藏,并留下你的观点哦!