package com.zksy.environment.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.StandardCharsets;

/**
 * @author Administrator
 * @version 1.0
 * @project datasynch
 * @description 数据编码器
 * @date 2023/11/16 14:02:56
 */
public class ResponseEncoder extends MessageToByteEncoder<String> {

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        byte[] content = msg.getBytes(StandardCharsets.UTF_8); // 将字符串转换为字节数组
        int length = content.length;

        out.writeInt(length); // 写入响应消息的长度
        out.writeBytes(content); // 写入响应消息的内容
    }
}
