Archived
0

refactoring: ProtocolEncoder

This commit is contained in:
2021-05-10 03:21:12 +03:00
parent f9a71250b1
commit 38918f5eaf
3 changed files with 16 additions and 22 deletions

View File

@@ -0,0 +1,10 @@
package mc.protocol;
import io.netty.util.AttributeKey;
import lombok.experimental.UtilityClass;
@UtilityClass
public class NettyAttributes {
public static final AttributeKey<State> STATE = AttributeKey.newInstance("STATE");
}

View File

@@ -0,0 +1,37 @@
package mc.protocol.codec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import mc.protocol.NettyAttributes;
import mc.protocol.State;
import mc.protocol.io.NetByteBuf;
import mc.protocol.packets.ServerSidePacket;
@Slf4j
public class ProtocolEncoder extends MessageToByteEncoder<ServerSidePacket> {
@Override
protected void encode(ChannelHandlerContext ctx, ServerSidePacket packet, ByteBuf out) {
State state = ctx.channel().attr(NettyAttributes.STATE).get();
Integer packetId = state.getServerSidePacketId(packet.getClass());
if (packetId == null) {
log.error("Unknown send packet: State {} ; Class {}", state, packet.getClass());
return;
}
if (log.isDebugEnabled()) {
log.debug("OUT: {}:{}", state, packet);
}
NetByteBuf buffer = new NetByteBuf(Unpooled.buffer());
buffer.writeVarInt(packetId);
packet.writeSelf(buffer);
NetByteBuf netByteBuf = new NetByteBuf(out);
netByteBuf.writeVarInt(buffer.readableBytes());
netByteBuf.writeBytes(buffer);
}
}