Archived
0

raw packet

This commit is contained in:
2018-04-08 18:08:36 +03:00
parent 5fc94d0ab0
commit 9602e6afc5
5 changed files with 117 additions and 1 deletions

View File

@@ -0,0 +1,8 @@
/*
* DmitriyMX <dimon550@gmail.com>
* 2018-04-08
*/
package mc.core;
public interface CSPacket {
}

View File

@@ -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()
);
}
};

View File

@@ -0,0 +1,71 @@
/*
* DmitriyMX <dimon550@gmail.com>
* 2018-04-08
*/
package mc.core.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import mc.core.netty.packets.RawPacket;
import java.util.List;
@Slf4j
public class PacketDecoder extends ByteToMessageDecoder {
private int readVarInt(ByteBuf byteBuf) throws Exception {
int result = 0;
byte read;
byte 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;
}
private int sizeVarInt(final int value) {
byte size = 0;
int v = value;
do {
v >>>= 7;
size++;
} while (v != 0);
return size;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
log.debug("ByteBuf readableBytes: {}", in.readableBytes());
int size = readVarInt(in);
log.debug("Pkt-Size: {}", size);
int id = readVarInt(in);
log.debug("Pkt-Id: {}", id);
byte[] rawData;
if (size > in.readableBytes()) {
rawData = new byte[in.readableBytes()];
} else {
rawData = new byte[size - sizeVarInt(id)];
}
in.readBytes(rawData);
RawPacket packet = new RawPacket();
packet.setRawData(rawData);
out.add(packet);
log.debug("ByteBuf readableBytes: {}", in.readableBytes());
in.skipBytes(in.readableBytes());
}
}

View File

@@ -0,0 +1,18 @@
/*
* DmitriyMX <dimon550@gmail.com>
* 2018-04-08
*/
package mc.core.netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import mc.core.CSPacket;
@Slf4j
public class PacketHandler extends SimpleChannelInboundHandler<CSPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, CSPacket packet) throws Exception {
log.info("{}: {}", packet.getClass().getSimpleName(), packet.toString());
}
}

View File

@@ -0,0 +1,17 @@
/*
* DmitriyMX <dimon550@gmail.com>
* 2018-04-08
*/
package mc.core.netty.packets;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import mc.core.CSPacket;
@ToString
public class RawPacket implements CSPacket {
@Getter
@Setter
private byte[] rawData;
}