0 votes

I was exploring how to create a lobby, i used the code below but i noticed that the create_client function always "connect" (print connect) to a server if I specify any valid IP address, regardless if a server actually exist. No error is shown.

func start_connection():
 SERVER_IP=#my IP
 SERVER_PORT=#any port, it doesnt care
 connection_thread.start(self, "create_client", null)

func create_client(_x):
    var peer = NetworkedMultiplayerENet.new()
    peer.create_client(SERVER_IP, SERVER_PORT)
    get_tree().set_network_peer(peer)
    get_tree().set_meta("network_peer", peer)
    call_deferred("close_connection_thread")

func close_connection_thread():
   connection_thread.wait_to_finish()
    if get_tree().network_peer==null:
        print("failed connection attempt")
    else:
        print("connected")

what am i doing wrong?
i am assuming if a peer is created, then the connection exist, is it correct?

Godot version 3.2.3
in Engine by (1,436 points)
edited by

1 Answer

0 votes
Best answer
func _enter_tree() -> void:
  get_tree().connect("connected_to_server", self, "_server_connected")
  get_tree().connect("connection_failed", self, "_server_connection_failed")


func _server_connected() -> void:
  print("connected")

# Timeouts after like 30s, so you may want to manually disconnect after 4 seconds, if either this or the _server_connected is still not called
func _server_connection_failed():
  print("failed")
by (398 points)
selected by

thank you for the answer, i knew this approach works from the docs, but it is not exactly what i'm looking for: in fact i can only check connection to the server via the initial connected/failed signal, while i would like to perform this check at any moment i wish.

i guess i can work with this set up though

If you mean being able to check the connection status at any time

enum {DISCONNECTED, CONNECTING, CONNECTED}

func get_connection_status() -> int:
    var network_peer := get_tree.network_peer
    if network_peer:
        return network_peer.get_connection_status()
    return DISCONNECTED

I personally discourage singletons, but might need it here, so you won't have to type this code again

that's it! get_connection_status() is what i was looking for before.
i eventually ended up writing a working code with the signals as you suggested (so double thank you), but it's good to know there is another way

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.