summaryrefslogtreecommitdiff
path: root/network/server.gd
diff options
context:
space:
mode:
Diffstat (limited to 'network/server.gd')
-rw-r--r--network/server.gd44
1 files changed, 44 insertions, 0 deletions
diff --git a/network/server.gd b/network/server.gd
new file mode 100644
index 0000000..e46e797
--- /dev/null
+++ b/network/server.gd
@@ -0,0 +1,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())