package dev.elaine.network;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public final class NettyFrameSample {
    private NettyFrameSample() {}

    public static String roundTrip(String message) {
        ByteBuf wire = Unpooled.buffer();
        EmbeddedChannel encoder = new EmbeddedChannel(
                new LengthFieldPrepender(4), new StringEncoder(CharsetUtil.UTF_8));
        try {
            encoder.writeOutbound(message);
            ByteBuf part;
            while ((part = encoder.readOutbound()) != null) {
                try {
                    wire.writeBytes(part);
                } finally {
                    ReferenceCountUtil.release(part);
                }
            }
        } finally {
            encoder.finishAndReleaseAll();
        }

        EmbeddedChannel decoder = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4),
                new StringDecoder(CharsetUtil.UTF_8));
        try {
            decoder.writeInbound(wire);
            return decoder.readInbound();
        } finally {
            decoder.finishAndReleaseAll();
        }
    }

    public static void main(String[] args) {
        System.out.println(roundTrip("一个完整消息"));
    }
}
