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

15
network/client/Client.gd Normal file
View File

@ -0,0 +1,15 @@
extends NetworkNode
@export var ip := "127.0.0.1"
@export var port := 4242
var socket := PacketPeerUDP.new()
func _init():
super._init()
socket.connect_to_host(ip, port)
func _process(_delta):
while socket.get_available_packet_count() > 0:
var packet := socket.get_packet()
handle_packet(packet, socket)

33
network/client/Login.gd Normal file
View File

@ -0,0 +1,33 @@
extends PacketHandler
@export var playerScene: PackedScene
var logged_in := false
func _ready():
%Client.set_handler(Packet.LOGIN, self)
send_login()
func send_login():
if logged_in:
return
var buffer := StreamPeerBuffer.new()
buffer.put_8(Packet.LOGIN)
buffer.put_data(JSON.stringify(["username", "password"]).to_utf8_buffer())
%Client.socket.put_packet(buffer.data_array)
print("[Client] Connecting...")
func handle_packet(data: PackedByteArray, _peer: PacketPeer):
if data[0] != 0:
print("[Client] Login failed.")
return
print("[Client] Login succeeded.")
logged_in = true
Global.player = spawn_player()
func spawn_player() -> Player:
var player = playerScene.instantiate()
%Players.add_child(player)
return player

32
network/client/Ping.gd Normal file
View File

@ -0,0 +1,32 @@
extends PacketHandler
signal changed(ping: float)
const HISTORY_SIZE = 8
var count := 0
var history: Array[float] = []
func _init():
history.resize(HISTORY_SIZE)
func _ready():
%Client.set_handler(Packet.PING, self)
func send_ping():
var buffer := StreamPeerBuffer.new()
buffer.put_8(Packet.PING)
buffer.put_8(count)
%Client.socket.put_packet(buffer.data_array)
history[count] = Time.get_unix_time_from_system()
count += 1
if count >= HISTORY_SIZE:
count = 0
func handle_packet(data: PackedByteArray, _peer: PacketPeer):
var id := data[0]
var ping := Time.get_unix_time_from_system() - history[id]
changed.emit(ping)