Created
May 22, 2020 23:47
-
-
Save RKiemGames/dc18c122138a14a2ba4fbbcea953e564 to your computer and use it in GitHub Desktop.
Persistent client connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
class_name NetworkedConnect | |
var _connected_to_server = false | |
var _connection_alive = Timer.new() | |
var _host | |
var _port | |
var _debug = false | |
func _init(host, port): | |
_host = host | |
_port = port | |
func _ready(): | |
_connection_alive.connect("timeout", self, "peer_connection_alive") | |
add_child(_connection_alive) | |
func debug(start=true): | |
_debug = start | |
func is_connection_alive(): | |
return _connected_to_server | |
func peer_connection_ok(): | |
if _debug: | |
print('connection to %s:%d successful' % [_host, _port]) | |
_connected_to_server = true | |
_connection_alive.start() | |
func peer_connection_alive(): | |
var status = get_tree().network_peer.get_connection_status() | |
if status != 2: | |
get_tree().network_peer = null | |
_connection_alive.stop() | |
_connected_to_server = false | |
start() | |
if _debug and status != 2: | |
prints('connection status:', status) | |
func start(): | |
var retry_count = 0 | |
var peer = NetworkedMultiplayerENet.new() | |
peer.create_client(_host, _port) | |
peer.connect('connection_succeeded', self, 'peer_connection_ok') | |
get_tree().network_peer = peer | |
while not _connected_to_server: | |
if _debug: | |
prints('waiting for server %s:%d tries: %d' % [_host, _port, retry_count+1]) | |
yield(get_tree().create_timer(1), 'timeout') | |
retry_count += 1 | |
if retry_count >= 15: | |
get_tree().network_peer = null | |
start() | |
break | |
return true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment