Improved network handling
This commit is contained in:
26
network/Login.gd
Normal file
26
network/Login.gd
Normal file
@ -0,0 +1,26 @@
|
||||
extends Node
|
||||
|
||||
const PLAYER = preload("res://player/Player.tscn")
|
||||
|
||||
func _ready():
|
||||
%Network.add_handler(%Network.Packet.LOGIN, self)
|
||||
send_login()
|
||||
|
||||
func send_login():
|
||||
var buffer := StreamPeerBuffer.new()
|
||||
buffer.put_8(%Network.Packet.LOGIN)
|
||||
buffer.put_data("password".to_utf8_buffer())
|
||||
%Network.udp.put_packet(buffer.data_array)
|
||||
print("Connecting...")
|
||||
|
||||
func handle_packet(data: PackedByteArray):
|
||||
if data[1] != 0:
|
||||
print("Login failed.")
|
||||
return
|
||||
|
||||
print("Login succeeded.", data)
|
||||
spawn_player()
|
||||
|
||||
func spawn_player():
|
||||
var player = PLAYER.instantiate()
|
||||
add_child(player)
|
33
network/Network.gd
Normal file
33
network/Network.gd
Normal file
@ -0,0 +1,33 @@
|
||||
extends Node
|
||||
|
||||
var udp := PacketPeerUDP.new()
|
||||
var handlers: Array[Node] = []
|
||||
|
||||
enum Packet {
|
||||
PING = 1,
|
||||
LOGIN = 2,
|
||||
LOGOUT = 3,
|
||||
MOVE = 10,
|
||||
}
|
||||
|
||||
func _init():
|
||||
handlers.resize(256)
|
||||
udp.connect_to_host("127.0.0.1", 4242)
|
||||
|
||||
func _process(_delta):
|
||||
if udp.get_available_packet_count() <= 0:
|
||||
return
|
||||
|
||||
var packet := udp.get_packet()
|
||||
var type := packet.decode_u8(0) as Packet
|
||||
var handler := handlers[type]
|
||||
|
||||
if handler == null:
|
||||
push_warning("Unknown packet type %d" % type)
|
||||
return
|
||||
|
||||
handler.handle_packet(packet)
|
||||
|
||||
func add_handler(packet: Packet, node: Node):
|
||||
assert(node.has_method("handle_packet"))
|
||||
handlers[packet] = node
|
38
network/Ping.gd
Normal file
38
network/Ping.gd
Normal file
@ -0,0 +1,38 @@
|
||||
extends Node
|
||||
|
||||
signal changed(ping: float)
|
||||
|
||||
const HISTORY_SIZE = 8
|
||||
|
||||
var count := 0
|
||||
var history: Array[float] = []
|
||||
|
||||
func _init():
|
||||
history.resize(HISTORY_SIZE)
|
||||
|
||||
func _ready():
|
||||
%Network.add_handler(%Network.Packet.PING, self)
|
||||
var timer := Timer.new()
|
||||
add_child(timer)
|
||||
timer.wait_time = 1
|
||||
timer.timeout.connect(_ping)
|
||||
timer.start()
|
||||
|
||||
func _ping():
|
||||
var buffer := StreamPeerBuffer.new()
|
||||
buffer.put_8(%Network.Packet.PING)
|
||||
buffer.put_8(count)
|
||||
%Network.udp.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):
|
||||
print("Handled ping!", data)
|
||||
var id := data.decode_u8(1)
|
||||
var ping := Time.get_unix_time_from_system() - history[id]
|
||||
changed.emit(ping)
|
||||
|
Reference in New Issue
Block a user