This repository has been archived by the owner on Jun 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
packets.go
72 lines (59 loc) · 2.07 KB
/
packets.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package mcproto
import (
"io"
"github.com/BRA1L0R/go-mcproto/packets"
)
// SerializablePacket defines the standard methods that a struct should have
// in order to be serializable by the library
//
// You can actually create your own methods as long as they respect this standard
type SerializablePacket interface {
// SerializeData takes an interface pointer as input and serializes all the fields in the
// data buffer. It can and will return an error in case of invalid data
SerializeData(inter interface{}) error
SerializeCompressed(writer io.Writer, compressionTreshold int) error
SerializeUncompressed(writer io.Writer) error
}
// WritePacket calls SerializeData and then calls WriteRawPacket
func (mc *Client) WritePacket(packet SerializablePacket) error {
mc.writeMu.Lock()
defer mc.writeMu.Unlock()
if err := packet.SerializeData(packet); err != nil {
return err
}
if mc.IsCompressionEnabled() {
return packet.SerializeCompressed(mc.connection, int(mc.CompressionTreshold))
} else {
return packet.SerializeUncompressed(mc.connection)
}
}
// WriteRawPacket takes a rawpacket as input and serializes it in the connection
func (mc *Client) WriteRawPacket(rawPacket *packets.MinecraftRawPacket) error {
mc.writeMu.Lock()
defer mc.writeMu.Unlock()
if mc.IsCompressionEnabled() {
return rawPacket.WriteCompressed(mc.connection)
} else {
return rawPacket.WriteUncompressed(mc.connection)
}
}
// ReceiveRawPacket reads a raw packet from the connection but doesn't deserialize
// neither uncompress it
func (mc *Client) ReceiveRawPacket() (*packets.MinecraftRawPacket, error) {
mc.readMu.Lock()
defer mc.readMu.Unlock()
if mc.IsCompressionEnabled() {
return packets.FromCompressedReader(mc.connection)
} else {
return packets.FromUncompressedReader(mc.connection)
}
}
// ReceivePacket receives and deserializes a packet from the connection, uncompressing it
// if necessary
func (mc *Client) ReceivePacket() (*packets.MinecraftPacket, error) {
rawPacket, err := mc.ReceiveRawPacket()
if err != nil {
return nil, err
}
return packets.FromRawPacket(rawPacket)
}