public class Networking : MonoBehaviour {
/**
* The number of additional times to retry connecting to host
* */
public int NumJoinAttempts = 3;
/**
* Time (in seconds) between each reconnection attempts
* */
public int TimeoutTime = 10;
public int serverTcpPort = 5127;
// Use this for initialization
void Start () {
TNManager.StartUDP(Random.Range(10000, 50000));
}
void OnApplicationQuit(){
TNServerInstance.Stop("server.dat");
}
public void StartServer(string accessCode) {
int udpPort = Random.Range(10000, 40000);
TNUdpLobbyClient lan = GetComponent<TNUdpLobbyClient>();
int lobbyPort = (lan !=null) ? lan.remotePort : 0;
var ip = Network.player.ipAddress;
var name = accessCode+"%"+ip;
TNServerInstance.serverName = name;
TNServerInstance.Start(serverTcpPort, udpPort, "server.dat", lobbyPort);
TNManager.Connect(ip, serverTcpPort);
}
public void JoinServer(string accessCode) {
StartCoroutine(AttemptJoinServer(accessCode, 0));
}
IEnumerator AttemptJoinServer(string accessCode, int attempt) {
// Check currently known servers for given access code
var list = TNLobbyClient.knownServers.list;
foreach (var server in list) {
var splitName = server.name.Split('%');
if (splitName[0] == accessCode) {
var ip = splitName[1];
TNManager.Connect(ip, serverTcpPort);
yield break;
}
}
yield return new WaitForSeconds
(TimeoutTime
);
// Check if already connected to the server
if (TNManager.isConnected || TNManager.isTryingToConnect)
yield break;
if (++attempt <=NumJoinAttempts) {
OnTimeOutHandlers(true, attempt, NumJoinAttempts);
StartCoroutine(AttemptJoinServer(accessCode, attempt));
}
else
OnTimeOutHandlers(false, attempt, NumJoinAttempts);
}
void OnNetworkConnect(bool success, string message) {
if (!success) return;
TNManager.JoinChannel(1, "");
}
void OnNetworkJoinChannel(bool success, string message) {
if (!success) return;
if (!TNManager.isHosting) {
OnJoinChannelHandlers(true);
}
}
}