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)