70 lines
1.7 KiB
GDScript
70 lines
1.7 KiB
GDScript
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 last_statistics := Time.get_ticks_msec()
|
|
var clients := {}
|
|
var packet_count := 0
|
|
var now := 0
|
|
|
|
func _init():
|
|
super._init()
|
|
server.set_max_pending_connections(max_pending_connections)
|
|
server.listen(port)
|
|
|
|
func _process(_delta):
|
|
server.poll()
|
|
now = Time.get_ticks_msec()
|
|
|
|
# Accept new connections
|
|
while server.is_connection_available():
|
|
var peer: PacketPeerUDP = server.take_connection()
|
|
var address := "%s:%d" % [peer.get_packet_ip(), peer.get_packet_port()]
|
|
|
|
if !clients.has(address):
|
|
var connection = Connection.new()
|
|
connection.peer = peer
|
|
connection.address = address
|
|
clients[address] = connection
|
|
peer_connected(connection)
|
|
|
|
clients[address].last_packet = now
|
|
|
|
# Process packets from clients
|
|
for key in clients:
|
|
var client = clients[key]
|
|
var peer = client.peer
|
|
|
|
while peer.get_available_packet_count() > 0:
|
|
var packet = peer.get_packet()
|
|
handle_packet(packet, peer)
|
|
client.last_packet = now
|
|
packet_count += 1
|
|
|
|
# Show statistics
|
|
if now > last_statistics + 1000:
|
|
for address in clients.keys():
|
|
var last_packet_time = clients[address].last_packet
|
|
|
|
if now - last_packet_time > timeout:
|
|
peer_disconnected(address)
|
|
clients.erase(address)
|
|
|
|
print("[Server] %d clients | %d packets" % [clients.size(), packet_count])
|
|
packet_count = 0
|
|
last_statistics = Time.get_ticks_msec()
|
|
|
|
func peer_connected(c: Connection):
|
|
print("[Server] Connected: ", c.address)
|
|
|
|
func peer_disconnected(c: Connection):
|
|
print("[Server] Disconnected: ", c.address)
|