Reset network client/server

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Legorel

I’m using a function named start_client or start_server to start the server and the client, but i want it able to be runned multiple times if needed.
I first had this:

var network = NetworkedMultiplayerENet.new()
 
func create_server() -> void:
  network.create_server(5555, 10)
  get_tree().set_network_peer(network)

But i was getting this error: create_server: The multiplayer instance is already active

I then tried this:

var network = NetworkedMultiplayerENet.new()

func create_server() -> void:
  network = NetworkedMultiplayerENet.new()
  network.create_server(5555, 10)
  get_tree().set_network_peer(network)

No errors this time, but for some reason, the client wasn’t able to connect to the server. I tried multiple times but couldn’t get it to work a single time.

And lastly i tried this:

var network = NetworkedMultiplayerENet.new()

func create_server() -> void:
  network.close_connection()
  network.create_server(5555, 10)
  get_tree().set_network_peer(network)

And i got this error: close_connection: The multiplayer instance isn't currently active

I couldn’t find any way to test if the client/server was already created. I could probably use a boolean to keep track of the network state but I want ot know if there is a cleaner way to achieve this.

:bust_in_silhouette: Reply From: Wakatta

You’d be surprised how a well placed yield works wonders

I find it very odd that NetworkedMultiplayerENet throws and error when trying to create a server if a server already exists. Like isn’t that the whole point of returning an error value?

Anyway your answer…

func restart_server():
    start_client()
    yield(get_tree().create_timer(2), "timeout")
    if network.get_connection_status() == network.CONNECTION_CONNECTING:
        network.close_connection()
        start_server()

My guess is you may have another server running elsewhere so basically you start a client and try to connect to the server and if it’s still connecting in 2 seconds there is no server so close and start server

Forgot to mention also connect the "server_disconnected" signal from the root node and ensure to use network.close_connection() there too

Wakatta | 2021-04-23 00:44

I forgot to mention that my client and server are on different projects, the yield method did not work but I saw you used get_connection_status().
I changed it a little and now it works:

var network = NetworkedMultiplayerENet.new()

func create_server() -> void:
  if network.get_connection_status() != network.CONNECTION_DISCONNECTED:
    network.close_connection()
  network.create_client(5555, 10)
  get_tree().set_network_peer(network)

Legorel | 2021-04-23 19:01

Wow completely forgot it had the disconnected tag.
And your approach is better

Wakatta | 2021-04-23 22:36