package com.netty;


import com.haobang.config.AppConfig;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.Charset;

/**
 * TCP 通道初始化器
 */
public class SyslogTcpChannelInitializer extends ChannelInitializer<SocketChannel> {
    private static final int MAX_FRAME_LENGTH = AppConfig.getSyslogMaxFrameLength();
    private static final Charset SYSLOG_CHARSET = AppConfig.getSyslogCharset();

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 添加基于分隔符的帧解码器，处理以换行符结尾的 Syslog 消息
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
                MAX_FRAME_LENGTH,
                Delimiters.lineDelimiter()));

        // 添加字符串解码器和编码器（使用可配置的字符集）
        pipeline.addLast("decoder", new StringDecoder(SYSLOG_CHARSET));
        pipeline.addLast("encoder", new StringEncoder(SYSLOG_CHARSET));

        // 添加业务处理器
        pipeline.addLast("handler", new SyslogMessageHandler());
    }
}