All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.liubs.shadowrpcfly.server.handler.MessageHandler Maven / Gradle / Ivy

There is a newer version: 1.0.3
Show newest version
package com.liubs.shadowrpcfly.server.handler;

import com.liubs.shadowrpcfly.logging.Logger;
import com.liubs.shadowrpcfly.server.module.ModulePool;
import com.liubs.shadowrpcfly.server.module.SerializeModule;
import com.liubs.shadowrpcfly.protocol.HeartBeatMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;


import java.util.List;

/**
 * 消息的压缩和解压缩
 * @author Liubsyy
 * @date 2023/12/15 10:01 PM
 **/
public class MessageHandler extends ByteToMessageCodec {
    private static final Logger logger = Logger.getLogger(MessageHandler.class);

    private SerializeModule serializeModule = ModulePool.getModule(SerializeModule.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        byte[] data;
        if(msg instanceof HeartBeatMessage) {
            //心跳消息
            data = HeartBeatMessage.getHearBeatMsg();
        }else {
            data = serializeModule.serialize(msg);
        }

        int dataLength = data.length;
        out.writeInt(dataLength); // 先写入消息长度
        out.writeBytes(data); // 写入序列化后的数据
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
        int readableBytes = in.readableBytes();
        if(readableBytes <= 0){
            return;
        }
        byte[] data = new byte[readableBytes];

        in.readBytes(data);

        if(HeartBeatMessage.isHeartBeatMsg(data)) {
            logger.info("收到心跳消息...");
        }else {
            Object obj = serializeModule.deserializeRequest(data);
            out.add(obj);
        }
    }

}