I am a beginner in Golang. And I had a problem with reading packets from Minecraft clients lately.
My program read packets from the connection in this way.
player := &Player{
conn: conn,
state: HANDSHAKING,
io: &ConnReadWrite{
rdr: bufio.NewReader(conn),
wtr: bufio.NewWriter(conn),
},
inaddr: InAddr{
"",
0,
},
keepalive: 0,
compression: false
}
func (player *Player) ReadVarInt() (i int, err error) {
val, _ := binary.ReadUvarint(player.io)
return int(val), nil
}
It worked correctly when the connection was just established, but later it cannot read the packet ID correctly.
I have worked for days, and I tried to rewrite it to copy wiki.vg's solution, but it seemed that it doesn't work
PS: My copy and the original one
val, length := 0, 0
for {
current, err := player.io.ReadByte()
if err != nil {
return 0, err
}
val |= int((current & 0x7F) << (length * 7))
length += 1
if length > 5 {
return 0, errors.New(fmt.Sprintf("%s: VarInt is too big", player.name))
}
if val&0x80 != 0x80 {
break
}
}
return int(val), nil
int value = 0;
int length = 0;
byte currentByte;
while (true) {
currentByte = readByte();
value |= (currentByte & 0x7F) << (length * 7);
length += 1;
if (length > 5) {
throw new RuntimeException("VarInt is too big");
}
if ((value & 0x80) != 0x80) {
break;
}
}
return value;