This code works as expected wen exported to HTML5. It does not work if I run it from the editor on mac, i get disconnected immediately. From the documentation it seems it should work as long as I poll(). I should also mention this works fine against my own nodejs websocket server, it just seems to have issues with external 3rd party servers like echo.websocket.org server and the twitch irc server (which is actually what I'm eventually hoping to connect to.
extends Control
var client = WebSocketClient.new()
var write_mode = WebSocketPeer.WRITE_MODE_TEXT
func _ready():
client.connect("connection_established", self, "started")
client.connect("connection_error", self, "error")
client.connect("connection_closed", self, "closed")
client.connect("data_received", self, "read")
func start():
client.connect_to_url("ws://echo.websocket.org")
func _on_Button_pressed():
if client.get_connection_status() == WebSocketClient.CONNECTION_DISCONNECTED:
print('connecting')
start()
func _process(delta):
if client.get_connection_status() == WebSocketClient.CONNECTION_DISCONNECTED:
return
client.poll()
func started(protocol):
client.get_peer(1).put_packet(encode_data("hello there sir",write_mode))
func error(args):
print('error:')
print(args)
func closed(clean):
print('connection closed')
func read(p_id=1):
print('receiving data: ' + decode_data(client.get_peer(1).get_packet(),true))
func encode_data(data, mode):
return data.to_utf8() if mode == WebSocketPeer.WRITE_MODE_TEXT else var2bytes(data)
func decode_data(data, is_string):
return data.get_string_from_utf8() if is_string else bytes2var(data)