Added Godot based server

This commit is contained in:
2024-01-20 22:18:58 +01:00
parent ce699ee6db
commit 1f73d22cd6
28 changed files with 338 additions and 135 deletions

35
network/server/Login.gd Normal file
View File

@ -0,0 +1,35 @@
extends PacketHandler
enum {
SUCCESS = 0,
FAIL = 1,
}
func _ready():
%Server.set_handler(Packet.LOGIN, self)
func handle_packet(data: PackedByteArray, peer: PacketPeer):
var data_string = data.get_string_from_utf8()
var login_request = JSON.parse_string(data_string)
if login_request.size() < 2:
fail_login(peer)
return
var username = login_request[0]
var password = login_request[1]
if username != "username" || password != "password":
fail_login(peer)
return
var buffer := StreamPeerBuffer.new()
buffer.put_8(Packet.LOGIN)
buffer.put_8(SUCCESS)
peer.put_packet(buffer.data_array)
func fail_login(peer: PacketPeer):
var buffer := StreamPeerBuffer.new()
buffer.put_8(Packet.LOGIN)
buffer.put_8(FAIL)
peer.put_packet(buffer.data_array)

20
network/server/Ping.gd Normal file
View File

@ -0,0 +1,20 @@
extends PacketHandler
func _ready():
%Server.set_handler(Packet.PING, self)
func handle_packet(data: PackedByteArray, peer: PacketPeer):
# var response := PackedByteArray()
# response.resize(2)
# response.encode_u8(0, Packet.PING)
# response.encode_u8(1, data[0])
# peer.put_packet(response)
var buffer := StreamPeerBuffer.new()
buffer.put_8(Packet.PING)
if data.size() > 0:
buffer.put_8(data[0])
peer.put_packet(buffer.data_array)

29
network/server/Server.gd Normal file
View File

@ -0,0 +1,29 @@
extends NetworkNode
@export var port := 4242
@export var max_pending_connections := 4096
var server := UDPServer.new()
var last_statistics := Time.get_ticks_msec()
var packet_count := 0
func _init():
super._init()
server.set_max_pending_connections(max_pending_connections)
server.listen(port)
func _process(_delta):
server.poll()
while server.is_connection_available():
var peer: PacketPeerUDP = server.take_connection()
while peer.get_available_packet_count() > 0:
var packet = peer.get_packet()
handle_packet(packet, peer)
packet_count += 1
if Time.get_ticks_msec() > last_statistics + 1000:
print("[Server] %d packets per second" % packet_count)
packet_count = 0
last_statistics = Time.get_ticks_msec()