WebSocketPeer: reconnecting after closing connection

Godot Version

4.2.1

Question

I am trying to implement a failsafe in case internet connection is not established before WebSocketPeer attepts to connect to a url.

It works perfectly if internet is on, and connection gets established within a few seconds. However if I start my program while having no internet connection, it immideately returns ready_state 3, which stands for ‘connection closed’. Trying to reconnect from this state doesn’t work, as ready_state stays at 0 perpetually.

Relevant code:

var client = WebSocketPeer.new()
var state : int = 0

func connect_client(url):

client.connect_to_url(url)

func _process(delta):

 #Read connection state and received packets every frame

state = client.get_ready_state()
client.poll()
print(state)

#State 1 means connected
if state == 1:

   if ! connected:
   	
   	#Prints out message upon successful connection
   	connected = true
   	print("Connected to ", url, "; With protocol: ", client.get_selected_protocol())

if state == 3:

   #Get closing code
   var code = client.get_close_code()
   var reason = client.get_close_reason()
   print("Connection closed with code: ", code, "; reason: ", reason)
   connected = false
   
   connect_client(url)

What am I doing wrong here?

Make sure that WebSocketPeer.connect_to_url() does not fail the second time it tries to connect with something like:

func connect_client(url):
	var result = client.connect_to_url(url)
	if result != OK:
		print('Could not connect to url. Reason: %s' % error_string(result))

If it fails it may be a bug in the engine. Try opening an issue here Issues · godotengine/godot · GitHub filling the Bug Report form.

As a workaround you could try creating a new WebSocketPeer each time you try to connect to an url.