【发布时间】:2018-07-21 00:36:46
【问题描述】:
我正在学习 Netty,但被 ChannelHandler 的 channelInactive 和 exceptionCaught 弄糊涂了。
据我了解,当 Server 宕机时,Client 会收到 IOEException,但如果 Server 显式关闭 Channel,Client 会收到 WRITE_IDEL 事件,它可以自己定义后处理。
但是从下面的演示中,我得到了不同的结果。我关闭了服务器,客户端跳线到 channelInactive 方法,但没有异常捕获。
ClientHandler:
package echoclient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import java.io.IOException;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;
/**
* Created by lulijun on 2018/2/12.
*/
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("channel active");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channel inactive");
}
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
System.out.println("Client received: "+in.toString(CharsetUtil.UTF_8));
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleState state= ((IdleStateEvent) evt).state();
if (state == IdleState.WRITER_IDLE) {
// read timeout, break the channel
System.out.println("client write timeout");
SocketAddress remoteAddress = ctx.channel().remoteAddress();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("channel exception");
cause.printStackTrace();
if (cause instanceof IOException) {
SocketAddress remoteAddress = ctx.channel().remoteAddress();
// reconnect
ctx.channel().close();
ctx.connect(remoteAddress);
} else {
ctx.channel().close();
}
}
protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("Client received: "+msg.toString(CharsetUtil.UTF_8));
}
}
【问题讨论】:
标签: netty