com.feingto.iot.common.codec.MessageEncoder Maven / Gradle / Ivy
package com.feingto.iot.common.codec;
import com.feingto.iot.common.Constants;
import com.feingto.iot.common.model.custom.BaseMessage;
import com.feingto.iot.common.model.custom.LoginMessage;
import com.feingto.iot.common.model.custom.Message;
import com.feingto.iot.common.util.ParserKit;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* 报文编码器
*
* @author longfei
*/
public class MessageEncoder extends MessageToByteEncoder {
@Override
protected void encode(ChannelHandlerContext ctx, BaseMessage msg, ByteBuf out) {
byte[] buf;
byte protocol;
// 报文固定头部
out.writeByte(Constants.HEAD);
if (msg instanceof LoginMessage) {
LoginMessage message = (LoginMessage) msg;
buf = (ParserKit.stringToHex(32, message.id()) +
ParserKit.stringToHex(100, message.token()) +
ParserKit.encodeToHex(20, message.username()) +
ParserKit.encodeToHex(20, message.password()) +
ParserKit.encodeToHex(2, message.type())).getBytes();
protocol = message.protocol();
} else if (msg instanceof Message) {
Message message = (Message) msg;
buf = message.content().getBytes();
protocol = message.protocol();
} else {
return;
}
out.writeByte(protocol)
.writeInt(buf.length)
.writeBytes(buf)
// 报文固定尾部
.writeByte(Constants.TAIL);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy