class_name Server extends NetworkNode ## Port number. @export var port := 4242 ## Timeout in milliseconds. @export var timeout := 5000 ## Maximum number of pending connections. @export var max_pending_connections := 4096 var server := UDPServer.new() var clients := {} var packet_count := 0 var now := 0 func _init(): super._init() server.set_max_pending_connections(max_pending_connections) server.listen(port) Performance.add_custom_monitor("Server/Clients", get_client_count) Performance.add_custom_monitor("Server/Packets", get_packet_count) func _process(_delta): server.poll() func _physics_process(_delta): now = Time.get_ticks_msec() # Accept new connections while server.is_connection_available(): var peer := server.take_connection() peer_to_client(peer) # Process packets from clients for address in clients: var client = clients[address] var peer = client.peer while peer.get_available_packet_count() > 0: client.last_packet = now var packet = peer.get_packet() handle_packet(packet, peer) packet_count += 1 # Disconnect for address in clients.keys(): var client = clients[address] var last_packet_time = client.last_packet if now - last_packet_time > timeout: peer_disconnected(client) clients.erase(address) func broadcast(packet: PackedByteArray): for address in clients: clients[address].peer.put_packet(packet) func broadcast_others(packet: PackedByteArray, exclude: Client): for address in clients: var client = clients[address] if client == exclude: continue client.peer.put_packet(packet) func get_client_count() -> int: return clients.size() func get_packet_count() -> int: var tmp := packet_count packet_count = 0 return tmp func peer_address(peer: PacketPeerUDP): return "%s:%d" % [peer.get_packet_ip(), peer.get_packet_port()] func peer_connected(c: Client): print("[%s] Connected." % c.address) func peer_disconnected(c: Client): print("[%s] Disconnected." % c.address) if c.player: c.player.queue_free() func peer_to_client(peer: PacketPeerUDP) -> Client: var address = peer_address(peer) if !clients.has(address): var client = Client.new(peer, address) clients[address] = client peer_connected(client) return client return clients[address]