package com.lifeknight.relaymcbungeemain.network; import com.google.gson.JsonParser; import com.lifeknight.relaymcbungeemain.Main; import com.lifeknight.relayutils.network.Message; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import io.netty.util.CharsetUtil; import java.util.List; public class MessageCoder { public static final String SEPARATOR = ",,"; public static final JsonParser JSON_PARSER = new JsonParser(); public static class MessageDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { String raw = in.toString(CharsetUtil.US_ASCII); if (!raw.endsWith(SEPARATOR)) return; in.readCharSequence(raw.length(), CharsetUtil.US_ASCII); String[] messages = raw.split(SEPARATOR); for (String message : messages) { try { out.add(Message.fromJson(JSON_PARSER.parse(message).getAsJsonArray())); } catch (Exception exception) { Main.error("Attempted to read Message, error occurred (%s): %s", message, exception.getMessage()); } } } } public static class MessageEncoder extends MessageToByteEncoder { protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception { out.writeCharSequence(msg.toString() + SEPARATOR, CharsetUtil.US_ASCII); } } }