-
编码器
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class MyLongEncoder extends MessageToByteEncoder<Long> {
@Override
protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
out.writeLong(msg);
}
}
-
解码器
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class MyLongDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if(in.readableBytes()>=4){
out.add(in.readLong());
}
}
}
-
在客户端和服务端都加入编码器和解码器到pipeline中
- 客户端
ChannelPipeline pipeline = ch.pipeline();
//1 Long 编码器 解码器
pipeline.addLast(new MyLongEncoder());
pipeline.addLast(new MyLongDecoder());
//2 自定义处理器:通道连接成功后发送一个long
pipeline.addLast(new SimpleChannelInboundHandler<Long>() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Long x=1234l;
System.out.println("客户端发送long="+x);
ctx.channel().writeAndFlush(x);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
System.out.println("客户端收到long的负数="+(-msg));
}
});
- 服务端
ChannelPipeline pipeline = ch.pipeline();
//1 Long 编码器 解码器
pipeline.addLast(new MyLongEncoder());
pipeline.addLast(new MyLongDecoder());
//2 自定义处理器:通道连接成功后接收long
pipeline.addLast(new SimpleChannelInboundHandler<Long>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
System.out.println("服务器收到long="+msg);
System.out.println("服务器发送long的负数="+(-msg));
ctx.channel().writeAndFlush(-msg);
}
});