blob: e46e797036b8b8fc0151db2d8ff4019c654d5e19 (
plain)
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
|
class_name Server
signal received_packet(packet: Packet)
var host: String
var port: int
var peer: StreamPeerTCP = StreamPeerTCP.new()
@warning_ignore("shadowed_variable")
func _init(host: String, port: int) -> void:
self.host = host
self.port = port
peer.connect_to_host(host, port)
peer.poll()
## Emits [signal received_packet].
func listen() -> void:
if peer.get_status() == StreamPeerTCP.Status.STATUS_CONNECTED:
var raw_packet: PackedByteArray = peer.get_partial_data(2)[1]
if raw_packet.size() > 0:
var header = raw_packet.decode_u16(0)
if Constants.PacketDB.has(header):
var packet_type = Constants.PacketDB[header]
if packet_type.BYTE_LENGTH > 0:
raw_packet += peer.get_partial_data(packet_type.BYTE_LENGTH - 2)[1]
else:
var packet_length: PackedByteArray = peer.get_data(2)[1]
raw_packet += packet_length
raw_packet += peer.get_data(packet_length.decode_u16(0) - 4)[1]
var packet = packet_type.from_bytes(raw_packet)
received_packet.emit(packet)
else:
raw_packet.reverse()
print("Received unknown packet with header ", raw_packet.hex_encode())
|