创建一个Maven项目添加下面依赖
org.slf4jslf4j-api1.7.32ch.qos.logbacklogback-classic1.2.3org.projectlomboklombok1.18.24trueorg.codehaus.jacksonjackson-mapper-asl1.9.13com.alibabafastjson1.2.78io.nettynetty-all4.1.84.Final 编码解码器 package com.example.nettydemo.coder; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.nio.charset.StandardCharsets; public class NettyEncoder extends MessageToByteEncoder
{ public NettyEncoder() { } @Override protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception { byte[] byteMsg = msg.getBytes(StandardCharsets.UTF_8); int msgLength = byteMsg.length; ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(4 + byteMsg.length); buf.writeInt(msgLength); buf.writeBytes(byteMsg, 0, msgLength); out.writeBytes(buf); buf.release(); } } package com.example.nettydemo.coder; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import lombok.extern.slf4j.Slf4j; import java.nio.charset.StandardCharsets; import java.util.List; @Slf4j public class NettyDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List