refactoring: ProtocolEncoder
This commit is contained in:
10
protocol-new/src/main/java/mc/protocol/NettyAttributes.java
Normal file
10
protocol-new/src/main/java/mc/protocol/NettyAttributes.java
Normal 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");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user