base packet
This commit is contained in:
15
src/main/java/mc/core/netty/BasePacket.java
Normal file
15
src/main/java/mc/core/netty/BasePacket.java
Normal file
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* DmitriyMX <dimon550@gmail.com>
|
||||
* 2018-03-25
|
||||
*/
|
||||
package mc.core.netty;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Getter
|
||||
class BasePacket {
|
||||
private final int length;
|
||||
private final int id;
|
||||
}
|
||||
@@ -22,7 +22,9 @@ public class NettyServer implements Server {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel socketChannel) {
|
||||
socketChannel.pipeline().addLast(
|
||||
new LoggingHandler()
|
||||
new LoggingHandler(),
|
||||
new PacketDecoder(),
|
||||
new PacketHandler()
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
41
src/main/java/mc/core/netty/PacketDecoder.java
Normal file
41
src/main/java/mc/core/netty/PacketDecoder.java
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* DmitriyMX <dimon550@gmail.com>
|
||||
* 2018-03-25
|
||||
*/
|
||||
package mc.core.netty;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.codec.ReplayingDecoder;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PacketDecoder extends ReplayingDecoder<BasePacket> {
|
||||
private int readVarInt(ByteBuf byteBuf) throws Exception {
|
||||
int result = 0;
|
||||
byte read;
|
||||
int numRead = 0;
|
||||
|
||||
do {
|
||||
read = byteBuf.readByte();
|
||||
int value = (read & 0b01111111);
|
||||
result |= (value << (7 * numRead));
|
||||
|
||||
numRead++;
|
||||
if (numRead > 5) {
|
||||
throw new Exception("VarInt is too big");
|
||||
}
|
||||
} while ((read & 0b10000000) != 0);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> list) throws Exception {
|
||||
int length = readVarInt(byteBuf);
|
||||
int id = readVarInt(byteBuf);
|
||||
|
||||
list.add(new BasePacket(length, id));
|
||||
byteBuf.skipBytes(length);
|
||||
}
|
||||
}
|
||||
19
src/main/java/mc/core/netty/PacketHandler.java
Normal file
19
src/main/java/mc/core/netty/PacketHandler.java
Normal file
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* DmitriyMX <dimon550@gmail.com>
|
||||
* 2018-03-25
|
||||
*/
|
||||
package mc.core.netty;
|
||||
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
@Slf4j
|
||||
public class PacketHandler extends SimpleChannelInboundHandler<BasePacket> {
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext context, BasePacket packet) throws Exception {
|
||||
log.info("Lenght: {} | Id: {}",
|
||||
packet.getLength(),
|
||||
packet.getId());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user