blob: 8b41b4faaf7edebd0a6007c6ded1f3269364aa12 (
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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]
prints("Upcoming Length:", packet_length.decode_u16(0), "for =>")
var packet = packet_type.from_bytes(raw_packet)
received_packet.emit(packet)
var display_header = raw_packet.slice(0, 2)
display_header.reverse()
print("Received known packet with header ", display_header.hex_encode(), " = ", packet_type.get_global_name())
else:
raw_packet.reverse()
print("Received unknown packet with header ", raw_packet.hex_encode())
func send(packet: Packet) -> Error:
var display_header = packet.get_header()
display_header.reverse()
print("Sent packet with header ", display_header.hex_encode())
return send_raw(packet.to_bytes())
func send_raw(bytes: PackedByteArray) -> Error:
return peer.put_data(bytes)
|