Skip to content

Instantly share code, notes, and snippets.

@OmidH
Created January 13, 2016 12:12
Show Gist options
  • Save OmidH/d606d400afa75be2b276 to your computer and use it in GitHub Desktop.
Save OmidH/d606d400afa75be2b276 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;
using System.Collections;
public class Connector : MonoBehaviour {
int connectionAttemptCount;
NetworkClient client;
bool errorHappened;
void Start () {
StartClient ();
}
void StartClient()
{
client = new NetworkClient ();
client.RegisterHandler (MsgType.Connect, OnConnected);
client.RegisterHandler (MsgType.Disconnect, OnDisconnected);
client.RegisterHandler (MsgType.Error, OnError);
// short timeouts
var config = new ConnectionConfig();
config.ConnectTimeout = 100;
client.Configure (config, 1);
client.Connect ("2.2.2.2", 1234); // some non-connectable server to create a connection timeout
Debug.LogFormat ("New connection attempt {0}...",connectionAttemptCount);
}
void StopClient()
{
print ("Stopping client: hostid=" + (connectionAttemptCount));
// can't do it here, would spam this error: host id {0} has been already deleted
NetworkTransport.RemoveHost (0);
//client.Disconnect ();
client.UnregisterHandler (MsgType.Connect);
client.UnregisterHandler (MsgType.Disconnect);
client.UnregisterHandler (MsgType.Error);
client.Shutdown ();
client = null;
connectionAttemptCount += 1;
}
void OnConnected(NetworkMessage netMsg)
{
print ("connected");
}
private void OnDisconnected(NetworkMessage netMsg)
{
print("disconnected");
StartCoroutine(Reset());
}
IEnumerator Reset()
{
StopClient();
yield return new WaitForSeconds(1);
StartClient();
}
void OnError(NetworkMessage netMsg)
{
// we just assume it's a timeout error
errorHappened = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment