using UnityEngine;
using TNet;
using System.IO;
using System.Collections;
using UnityTools = TNet.UnityTools;
[ExecuteInEditMode]
public class tnetMultiplayerExample : TNEventReceiver {
//TNET variables start
static tnetMultiplayerExample mInst = null;
public enum IPType
{
IP_v_4,
IP_v_6,
}
string serverName;
int knownServers;
public bool serverCrerated = false;
TNServerInstance ourServer;
public int serverTcpPort = 5127;
public IPType addressFamily = IPType.IP_v_4;
//TNET variables end
//public string [] serverList;
public ServerList.Entry [] serverListInfo;
public ServerList.Entry myServer;
public int totalServers;
public bool updatingList;
bool hosting = false;
protected static tnetMultiplayerExample _instance;
public static tnetMultiplayerExample instance { get { return _instance; } }
void Awake () {
if (Application.isPlaying)
{
// Choose IPv6 or IPv4
TcpProtocol.defaultListenerInterface = (addressFamily == IPType.IP_v_6) ? System.Net.IPAddress.IPv6Any : System.Net.IPAddress.Any;
// TNet will automatically switch UDP to IPv6 if TCP uses it, but you can specify an explicit one if you like
//UdpProtocol.defaultNetworkInterface = useIPv6 ? System.Net.IPAddress.IPv6Any : System.Net.IPAddress.Any;
if (mInst == null)
{
mInst = this;
DontDestroyOnLoad(gameObject);
}
else Destroy(gameObject);
}
}
void Start () {
}
void Update () {
}
void OnEnable () {
TNManager.onConnect += OnConnect;
TNManager.onJoinChannel += OnJoinChannel;
TNManager.onPlayerJoin += OnPlayerJoin;
TNManager.onPlayerLeave += OnPlayerLeave;
TNManager.onDisconnect += OnDisconnect;
TNManager.onLeaveChannel += OnLeaveChannel;
}
public void StartServer (string newServerName) {
if (TNLobbyClient.knownServers.list.size > 0) { //check if an old server is still alive and kicking first
//serverName
for (int i = TNLobbyClient.knownServers.list.size - 1; i > -1; i--) {
if (TNLobbyClient.knownServers.list [i].name == serverName) {
StartCoroutine (CheckForOldHostGame ());
Debug.Log ("OLD SERVER IS STILL ACTIVE!!!");
return;
}
}
}
hosting = true;
int udpPort = Random.Range(10000, 40000);
TNLobbyClient lobby = GetComponent<TNLobbyClient>();
serverName = newServerName + "_" + (Random.Range(100000,900000)); //add a number to prevent duplicate server names;
if (lobby == null)
{
TNServerInstance.serverName = serverName;
if (TNServerInstance.Start (serverTcpPort, udpPort, "server.dat")) {
TNManager.Connect ();
}
}
else
{
TNServerInstance.serverName = serverName;
TNServerInstance
.Type type
= (lobby
is TNUdpLobbyClient
) ? TNServerInstance.Type.Udp : TNServerInstance.Type.Tcp;
if (TNServerInstance.Start(serverTcpPort, udpPort, lobby.remotePort, "server.dat", type))
TNManager.Connect();
}
StartCoroutine (WaitForServerInit ());
}
IEnumerator CheckForOldHostGame () {
bool oldGameExists = true;
float nextCheck = Time.time + 1;
while (oldGameExists) {
if (Time.time > nextCheck) {
if (TNLobbyClient.knownServers.list.size > 0) { //check if an old server is still alive and kicking first
oldGameExists = false;
for (int i = TNLobbyClient.knownServers.list.size - 1; i > -1; i--) {
if (TNLobbyClient.knownServers.list [i].name == serverName) {
oldGameExists = true;
}
}
if (!oldGameExists) {
Debug.Log ("Old game is now gone");
}
} else { //no servers now. So move on
Debug.Log ("Old game is still active");
oldGameExists = false;
}
}
yield return new WaitForSeconds
(1); }
}
IEnumerator WaitForServerInit () {
List<ServerList.Entry> list = TNLobbyClient.knownServers.list;
while (list.size == 0) {
list = TNLobbyClient.knownServers.list;
Debug.Log ("***List length:" + list.size);
yield return new WaitForSeconds
(1); }
Debug.Log ("***we've got a list! "+TNLobbyClient.knownServers.list.size);
myServer = null;
while (myServer == null) {
GetListOfGames ();
for (int i = serverListInfo.Length - 1; i > -1; i--) {
if (serverListInfo [i].name == TNServerInstance.serverName) {
myServer = serverListInfo [i];
break;
}
}
yield return new WaitForSeconds
(1); }
if (myServer.name != TNServerInstance.serverName) { //failed to find our server!
Debug.Log ("***FAILED TO FIND OUR OWN SERVER!!!");
//shut the server down and error out
} else {
TNManager.JoinChannel(1, "exampleScene",true,2,""); //Relaoding the same scene works
//TNManager.JoinChannel(1, null,true,2,""); //Loading no scene doesn't
}
}
public void GetListOfGames () {
totalServers = TNLobbyClient.knownServers.list.size;
if (totalServers == 0) {
Debug.Log ("No hosted games found");
return;
}
serverListInfo
= new ServerList
.Entry[totalServers
]; for (int i = TNLobbyClient.knownServers.list.size-1; i > -1; i--) {
Debug.Log ("Server #" + i + " name:" + TNLobbyClient.knownServers.list [i].name+" player count: "+TNLobbyClient.knownServers.list [i].playerCount);
serverListInfo [i] = TNLobbyClient.knownServers.list [i];
}
updatingList = false;
}
public void JoinHostedGame (string hostedGameName) {
myServer = null;
int serverNumber = -1;
for (int i = 0; i < serverListInfo.Length; i++) {
if (hostedGameName == serverListInfo [i].name) {
Debug.Log ("Found it! Joining now");
TNManager.Connect(serverListInfo [i].internalAddress, serverListInfo [i].internalAddress);
myServer = serverListInfo [i];
serverNumber = i;
break;
}
}
if (serverNumber == -1) {
Debug.Log ("***TELL PLAYER: THAT SERVER IS NO LONGER AVAILABLE");
}
}
void OnConnect (bool success, string message)
{
Debug.Log("*** Connected: " + success + " " + message + " (Player ID #" + TNManager.playerID + ")");
// Make it possible to use UDP using a random port
if (success && !TNServerInstance.isLocal) TNManager.StartUDP(Random.Range(10000, 50000));
if (hosting) {
serverCrerated = true;
} else {
TNManager.JoinChannel(1, "exampleScene",true,2,""); //Relaoding the same scene works
//TNManager.JoinChannel(1, null,true,2,""); //Loading no scene doesn't
}
}
void OnJoinChannel (int channelID, bool success, string msg)
{
if (hosting) {
Debug.Log ("***JOINED CHANNEL HOSTING!!!");
StartCoroutine (WaitForOtherPlayer ());
} else {
Debug.Log ("***JOINED CHANNEL as guest!!!");
}
Debug.Log("*** Joined channel #" + channelID + " " + success + " " + msg+" player count:"+myServer.playerCount);
}
IEnumerator WaitForOtherPlayer () {
Debug.Log ("*** OKAY!!! WAITING FOR SECOND PLAYER!!!");
while (myServer.playerCount < 2) {
yield return new WaitForSeconds
(.5f
); }
Debug.Log ("*** OKAY!!! SECOND PLAYER IS HERE!!!");
}
void OnDisconnect ()
{
Debug.Log("*** SOMEONE DISCONNECTED!!!! Are we still connected? "+TNManager.isConnected);
}
void OnLeaveChannel (int channelID)
{
Debug.Log("*** Left channel #" + channelID);
}
void onPlayerLeave (int channelID, Player p) {
Debug.Log ("*** A PLAYER JUST LEFT!!!");
}
void OnPlayerJoin (int channelID, Player p) {
Debug.Log ("*** OOOP! SOMEONE JUST JOINED!! Our ID:" + TNManager.playerID + " player added:" + p.id);
if (TNManager.isHosting) {
if (myServer.playerCount == 2) Debug.Log ("***TIME TO GET THE PARTY STARTED!!!");
}
}
void OnPlayerLeave (int channelID, Player p) {
Debug.Log ("*** OOOP! SOMEONE JUST LEFT!! Our ID:" + TNManager.playerID + " player added:" + p.id);
}
public void StopServer () {
hosting = false;
serverCrerated = false;
Debug.Log ("***SHUTTING DOWN THE SERVER");
TNManager.SetPlayerLimit (0);
if (TNManager.isInChannel) TNManager.LeaveChannel();
if (TNManager.isConnected) TNManager.Disconnect ();
TNServerInstance.Stop("server.dat");
}
}