com.feingto.iot.common.handler.DefaultSimpleChannelHandler Maven / Gradle / Ivy
package com.feingto.iot.common.handler;
import com.feingto.iot.common.exception.ServiceException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.MqttMessage;
import java.util.Optional;
/**
* 通道Inbound处理器抽象
*
* @author longfei
*/
public abstract class DefaultSimpleChannelHandler extends SimpleChannelInboundHandler {
public abstract void handleMessage(ChannelHandlerContext ctx, T msg) throws Exception;
@Override
protected void channelRead0(ChannelHandlerContext ctx, T msg) throws Exception {
if (msg instanceof MqttMessage) {
Optional.ofNullable(((MqttMessage) msg).fixedHeader())
.ifPresent(fixedHeader -> {
try {
handleMessage(ctx, msg);
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException(e.getMessage());
}
});
} else {
handleMessage(ctx, msg);
}
}
/**
* 当Channel上的某个读操作完成时被调用
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
/**
* 处理过程中ChannelPipeline中发生错误时被调用
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy