From d560f77811d4fc6f29bf477356a6d2e58dda0be1 Mon Sep 17 00:00:00 2001 From: Daniel Weipert Date: Sat, 30 Nov 2024 12:46:08 +0100 Subject: next commit --- network/server.gd | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 network/server.gd (limited to 'network/server.gd') 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()) -- cgit v1.2.3