Client/scripts/ui/websocket_time.gd

51 lines
1.3 KiB
GDScript3
Raw Normal View History

2025-01-29 13:43:42 +01:00
extends RichTextLabel
@export var login: Login
@export var api_config: ApiConfig
var api := ServerApi.new(api_config)
2025-01-29 13:43:42 +01:00
# docs.redotengine.org/en/stable/tutorials/networking/websocket.html
var time_channel = WebSocketPeer.new()
2025-01-29 13:43:42 +01:00
func _ready() -> void:
login.connect("login_successful", on_login)
(
ConnectionChannel
. connect(
"on_channel_token_received",
on_channel_token_received,
)
)
2025-01-29 13:43:42 +01:00
func on_login(session: PlayerLoginSession):
ConnectionChannel.connect_to_channel(session.token)
ConnectionChannel.request_channel_token(Message.Channels.TIME)
2025-01-29 13:43:42 +01:00
func on_channel_token_received(msg: ProvidedConnectionTokenMessage) -> void:
if time_channel.get_ready_state() != WebSocketPeer.STATE_CLOSED:
return
if msg.channel != Message.Channels.TIME:
2025-01-29 13:43:42 +01:00
return
time_channel.handshake_headers = PackedStringArray(
["Authorization: " + msg.token],
)
time_channel.connect_to_url("ws://localhost:8080/ws/time")
2025-01-29 13:43:42 +01:00
func _process(_delta: float) -> void:
time_channel.poll()
var state = time_channel.get_ready_state()
if state != WebSocketPeer.STATE_OPEN:
return
while time_channel.get_available_packet_count():
2025-03-04 15:25:27 +01:00
var msg: CurrentUnixTimeMessage = Messize(
time_channel.get_packet().get_string_from_utf8(), [CurrentUnixTimeMessage]
)
if msg == null:
continue
self.text = str(msg.time)