![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3bf034ac07c48d9cc89f61c92ab249c6.png)
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class MsgDecoder extends ByteToMessageDecoder {
private static final int HEAD_LENGTH = 4;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() < HEAD_LENGTH) {
return;
}
in.markReaderIndex();
int dataLength = in.readInt();
if (dataLength < 0) {
ctx.close();
}
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
return;
}
byte[] body = new byte[dataLength];
in.readBytes(body);
Object o = convertToObject(body);
System.out.println("bytes convert to Dog");
out.add(o);
}
private Object convertToObject(byte[] body) {
if (body == null || body.length < 1) {
return null;
}
String contentString = null;
try {
contentString = new String(body, "GBK");
} catch (Exception e) {
}
if (StringUtils.isBlank(contentString)) {
return null;
}
try {
Dog dog = JSON.parseObject(contentString, Dog.class);
return dog;
} catch (Exception e) {
System.out.println("bytes convert to Dog error. ");
e.printStackTrace();
}
return contentString;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0c302f7b3823429782dc0d37f52b6331.png)
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class MsgEncoder extends MessageToByteEncoder<Dog> {
@Override
protected void encode(ChannelHandlerContext ctx, Dog msg, ByteBuf out) throws Exception {
byte[] body = convertToBytes(msg);
System.out.println("Dog convert to bytes");
if (body == null || body.length < 1) {
return;
}
int dataLength = body.length;
out.writeInt(dataLength);
out.writeBytes(body);
}
private byte[] convertToBytes(Dog dog) {
if (dog == null) {
return null;
}
try {
String contentString = JSON.toJSONString(dog);
return contentString.getBytes("GBK");
} catch (Exception e) {
System.out.println("Dog convert to bytes error. ");
e.printStackTrace();
}
return null;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4f34f66f09ce6242b74235d24c9e6737.png)