我尝试发送带有净额的对象消息PingMessage
。在频道管道中添加ObjectEncoder
和ObjectDecoder
。客户端已成功发送数据包,但服务器无法解码该消息。 ObjectDecoder#decode()仅返回null。 Netty版本是4.1.28.Final。
PingMessage
public class PingMessage implements Serializable {
private static final long serialVersionUID = 1L;
private int flag = 0xff3e;
private String ping = "ping";
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getPing() {
return ping;
}
public void setPing(String ping) {
this.ping = ping;
}
}
客户端
public class HeartbeatInitializer extends ChannelInitializer<Channel> {
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ObjectEncoder());
pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingResolver(PongMessage.class.getClassLoader())));
pipeline.addLast(new IdleStateHandler(BusinessConstant.READER_IDLE_SECONDS, BusinessConstant.WRITER_IDLE_SECONDS, 0));
pipeline.addLast(new HeartbeatServerHandler());
pipeline.addLast(new ClientHandler());
}
}
public class HeartbeatServerHandler extends ChannelDuplexHandler {
private static Logger logger = LoggerFactory.getLogger(HeartbeatServerHandler.class);
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleState = (IdleStateEvent)evt;
if (idleState.state() == IdleState.READER_IDLE) {
} else if (idleState.state() == IdleState.WRITER_IDLE) {
try {
ChannelFuture future = ctx.writeAndFlush(new PingMessage()).sync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
服务器
public class HeartbeatInitializer extends ChannelInitializer<Channel> {
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ObjectEncoder());
pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingResolver(this.class.getClassLoader())));
pipeline.addLast(new IdleStateHandler(BusinessConstant.READER_IDLE_SECONDS, BusinessConstant.WRITER_IDLE_SECONDS, 0));
pipeline.addLast(new HeartbeatServerHandler());
pipeline.addLast(new ClientHandler());
}
}
public class HeartbeatServerHandler extends ChannelDuplexHandler {
private static Logger logger = LoggerFactory.getLogger(HeartbeatServerHandler.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof PingMessage) {
logger.info("received ping");
return;
}
}
}
netty源代码调试信息
AbstractChannelHandlerContext#invokeChannelRead()
((ChannelInboundHandler) handler()).channelRead(this, msg);
msg
变量是
UnpooledUnsafeDirectByteBuf(ridx:0,widx:61,cap:1024)
ObjectDecoder#decode()仅返回null
ObjectDecoder
的超类是LengthFieldBasedFrameDecoder
。 LengthFieldBasedFrameDecoder#decode()返回null
// LengthFieldBasedFrameDecoder#decode()
int frameLengthInt = (int) frameLength;
if (in.readableBytes() < frameLengthInt) {
return null; // get executed and return null
}