public class ChannelHandle extends SimpleChannelInboundHandler<ByteBuf> {
private IChannelHandle iChannelHandle;
public ChannelHandle(IChannelHandle iChannelHandle){
this.iChannelHandle = iChannelHandle;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
/**
* 发送时必须设置标记边界\n或\r\n ,否则会存在粘包拆包的情况
*/
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//处理接收到的数据msg
Log.d("ccc", "channelRead:---"+msg.toString());
}
@Override
protected void messageReceived(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
Log.e("ccc", "channelInactive 连接失败");
iChannelHandle.restart(true);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
Log.i("ccc", "exceptionCaught 连接错误回调");
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
Log.d("ccc", "channelRead:--- read1 idle");
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
if (idleStateEvent.state().equals(IdleState.WRITER_IDLE)) {
//写超时,此时可以发送心跳数据给服务器
Log.d("ccc", "channelRead write idle");
}else if (idleStateEvent.state().equals(IdleState.READER_IDLE)){
//读超时,此时代表没有收到心跳返回可以关闭当前连接进行重连
Log.d("ccc", "channelRead:--- read2 idle");
iChannelHandle.restart(true);
}
}
}
}