hexland/Scripts/WebsocketController.gd
2022-10-13 14:40:19 -05:00

57 lines
1.1 KiB
GDScript

extends Node
var client = WebSocketClient.new()
var ws
signal connected
signal chat
signal room_code
signal join_ok
func _init():
client.connect("connection_established", self, "_on_connect")
client.connect("data_received", self, "_on_data")
func _on_connect(_proto):
ws = client.get_peer(1)
ws.set_write_mode(WebSocketPeer.WRITE_MODE_TEXT)
emit_signal("connected")
func _on_data():
var msg = Message.new(ws.get_packet().get_string_from_utf8())
match msg.command:
"CHAT":
emit_signal("chat", msg.args[0])
"ROOM_CODE":
emit_signal("room_code", msg.args[0])
"JOIN_OK":
emit_signal("join_ok")
_:
print("Unknown command => ", msg)
func _process(_delta):
client.poll()
func send_message(message):
ws.put_packet(str(message).to_utf8())
func connect_websocket():
client.connect_to_url(ProjectSettings["global/server_url"]);
func host_game():
var msg = Message.new()
msg.command = "HOST"
send_message(msg)
func join_game(hash_):
var msg = Message.new()
msg.command = "JOIN"
msg.args.push_back(hash_)
send_message(msg)
func chat(text):
var msg = Message.new()
msg.command = "CHAT"
msg.args.push_back(text)
send_message(msg)