Files
godot-demo-projects/networking/websocket_chat/websocket/WebSocketClient.gd
Hugo Locurcio bac1e69164 Use static typing in all demos (#1063)
This leads to code that is easier to understand and runs
faster thanks to GDScript's typed instructions.

The untyped declaration warning is now enabled on all projects
where type hints were added. All projects currently run without
any untyped declration warnings.

Dodge the Creeps and Squash the Creeps demos intentionally don't
use type hints to match the documentation, where type hints haven't
been adopted yet (given its beginner focus).
2024-06-01 12:12:18 +02:00

74 lines
1.7 KiB
GDScript

class_name Node
extends WebSocketClient
@export var handshake_headers: PackedStringArray
@export var supported_protocols: PackedStringArray
var tls_options: TLSOptions = null
var socket := WebSocketPeer.new()
var last_state := WebSocketPeer.STATE_CLOSED
signal connected_to_server()
signal connection_closed()
signal message_received(message: Variant)
func connect_to_url(url: String) -> int:
socket.supported_protocols = supported_protocols
socket.handshake_headers = handshake_headers
var err := socket.connect_to_url(url, tls_options)
if err != OK:
return err
last_state = socket.get_ready_state()
return OK
func send(message: String) -> int:
if typeof(message) == TYPE_STRING:
return socket.send_text(message)
return socket.send(var_to_bytes(message))
func get_message() -> Variant:
if socket.get_available_packet_count() < 1:
return null
var pkt := socket.get_packet()
if socket.was_string_packet():
return pkt.get_string_from_utf8()
return bytes_to_var(pkt)
func close(code: int = 1000, reason: String = "") -> void:
socket.close(code, reason)
last_state = socket.get_ready_state()
func clear() -> void:
socket = WebSocketPeer.new()
last_state = socket.get_ready_state()
func get_socket() -> WebSocketPeer:
return socket
func poll() -> void:
if socket.get_ready_state() != socket.STATE_CLOSED:
socket.poll()
var state := socket.get_ready_state()
if last_state != state:
last_state = state
if state == socket.STATE_OPEN:
connected_to_server.emit()
elif state == socket.STATE_CLOSED:
connection_closed.emit()
while socket.get_ready_state() == socket.STATE_OPEN and socket.get_available_packet_count():
message_received.emit(get_message())
func _process(_delta: float) -> void:
poll()