A client manager which contains static client information and functions.
internal void RegisterSystemHandlers(bool localClient) { ClientScene.RegisterSystemHandlers(this, localClient); }
void OnGUI() { if (!showGUI) { return; } int xpos = 10 + offsetX; int ypos = 40 + offsetY; int spacing = 24 * (int)scale; style.alignment = TextAnchor.UpperLeft; GUI.Label(new Rect(xpos, 10, 300 * scale, 20 * scale), "IP=" + LocalIPAddress() + " port=" + manager.networkPort, style); if (!NetworkClient.active && !NetworkServer.active && manager.matchMaker == null) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "LAN Host(H)")) { manager.StartHost(); } ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 105 * scale, 20 * scale), "LAN Client(C)")) { manager.StartClient(); } style.alignment = TextAnchor.MiddleCenter; manager.networkAddress = GUI.TextField(new Rect(xpos + 105 * scale, ypos, 95 * scale, 20 * scale), manager.networkAddress, style); ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "LAN Server Only(S)")) { manager.StartServer(); } ypos += spacing; } else { if (NetworkServer.active) { GUI.Label(new Rect(xpos, ypos, 300 * scale, 20 * scale), "Server: port=" + manager.networkPort); ypos += spacing; } if (NetworkClient.active) { GUI.Label(new Rect(xpos, ypos, 300 * scale, 20 * scale), "Client: address=" + manager.networkAddress + " port=" + manager.networkPort); ypos += spacing; } } if (NetworkClient.active && !ClientScene.ready) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Client Ready")) { ClientScene.Ready(manager.client.connection); if (ClientScene.localPlayers.Count == 0) { ClientScene.AddPlayer(0); } } ypos += spacing; } if (NetworkServer.active || NetworkClient.active) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Stop (X)")) { manager.StopHost(); } ypos += spacing; } if (!NetworkServer.active && !NetworkClient.active) { ypos += 10; if (manager.matchMaker == null) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Enable Match Maker (M)")) { manager.StartMatchMaker(); } ypos += spacing; } else { if (manager.matchInfo == null) { if (manager.matches == null) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Create Internet Match")) { //manager.matchMaker.CreateMatch(manager.matchName, manager.matchSize, true, "", manager.OnMatchCreate); } ypos += spacing; GUI.Label(new Rect(xpos, ypos, 100 * scale, 20 * scale), "Room Name:"); manager.matchName = GUI.TextField(new Rect(xpos + 100, ypos, 100, 20), manager.matchName); ypos += spacing; ypos += 10; if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Find Internet Match")) { //manager.matchMaker.ListMatches(0,20, "", manager.OnMatchList); } ypos += spacing; } else { foreach (var match in manager.matches) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Join Match:" + match.name)) { manager.matchName = match.name; manager.matchSize = (uint)match.currentSize; //manager.matchMaker.JoinMatch(match.networkId, "", manager.OnMatchJoined); } ypos += spacing; } } } if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Change MM server")) { showServer = !showServer; } if (showServer) { ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 100 * scale, 20 * scale), "Local")) { manager.SetMatchHost("localhost", 1337, false); showServer = false; } ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 100 * scale, 20 * scale), "Internet")) { manager.SetMatchHost("mm.unet.unity3d.com", 443, true); showServer = false; } ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 100 * scale, 20 * scale), "Staging")) { manager.SetMatchHost("staging-mm.unet.unity3d.com", 443, true); showServer = false; } } ypos += spacing; GUI.Label(new Rect(xpos, ypos, 300 * scale, 20 * scale), "MM Uri: " + manager.matchMaker.baseUri); ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 200 * scale, 20 * scale), "Disable Match Maker")) { manager.StopMatchMaker(); } ypos += spacing; } } }
void OnGUI() { if (!showGUI) { return; } float xpos = 10 * scale_factor + offsetX; float ypos = 40 * scale_factor + offsetY; float spacing = 24 * scale_factor; bool noConnection = (manager.client == null || manager.client.connection == null || manager.client.connection.connectionId == -1); if (!manager.IsClientConnected() && !NetworkServer.active && manager.matchMaker == null) { if (noConnection) { if (UnityEngine.Application.platform != RuntimePlatform.WebGLPlayer) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "LAN Host(H)")) { manager.StartHost(); } ypos += spacing; } if (GUI.Button(new Rect(xpos, ypos, 100 * scale_factor, 20 * scale_factor), "LAN Client(C)")) { manager.StartClient(); } manager.networkAddress = GUI.TextField(new Rect(xpos + 100 * scale_factor, ypos, 100 * scale_factor, 20 * scale_factor), manager.networkAddress); ypos += spacing; if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) { // cant be a server in webgl build GUI.Box(new Rect(xpos, ypos, 200 * scale_factor, 25 * scale_factor), "( WebGL cannot be server )"); ypos += spacing; } else { if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "LAN Server Only(S)")) { manager.StartServer(); } ypos += spacing; } } else { GUI.Label(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Connecting to " + manager.networkAddress + ":" + manager.networkPort + ".."); ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Cancel Connection Attempt")) { manager.StopClient(); } } } else { if (NetworkServer.active) { string serverMsg = "Server: port=" + manager.networkPort; if (manager.useWebSockets) { serverMsg += " (Using WebSockets)"; } GUI.Label(new Rect(xpos, ypos, 300 * scale_factor, 20 * scale_factor), serverMsg); ypos += spacing; } if (manager.IsClientConnected()) { GUI.Label(new Rect(xpos, ypos, 300 * scale_factor, 20 * scale_factor), "Client: address=" + manager.networkAddress + " port=" + manager.networkPort); ypos += spacing; } } if (manager.IsClientConnected() && !ClientScene.ready) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Client Ready")) { ClientScene.Ready(manager.client.connection); if (ClientScene.localPlayers.Count == 0) { ClientScene.AddPlayer(0); } } ypos += spacing; } if (NetworkServer.active || manager.IsClientConnected()) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Stop (X)")) { manager.StopHost(); } ypos += spacing; } if (!NetworkServer.active && !manager.IsClientConnected() && noConnection) { ypos += 10; if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) { GUI.Box(new Rect(xpos - 5, ypos, 220 * scale_factor, 25 * scale_factor), "(WebGL cannot use Match Maker)"); return; } if (manager.matchMaker == null) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Enable Match Maker (M)")) { manager.StartMatchMaker(); } ypos += spacing; } else { if (manager.matchInfo == null) { if (manager.matches == null) { if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Create Internet Match")) { manager.matchMaker.CreateMatch(manager.matchName, manager.matchSize, true, "", "", "", 0, 0, manager.OnMatchCreate); } ypos += spacing; GUI.Label(new Rect(xpos, ypos, 100 * scale_factor, 20 * scale_factor), "Room Name:"); manager.matchName = GUI.TextField(new Rect(xpos + 100 * scale_factor, ypos, 100 * scale_factor, 20 * scale_factor), manager.matchName); ypos += spacing; ypos += 10; if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Find Internet Match")) { manager.matchMaker.ListMatches(0, 20, "", false, 0, 0, manager.OnMatchList); } ypos += spacing; } else { for (int i = 0; i < manager.matches.Count; i++) { var match = manager.matches[i]; if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Join Match:" + match.name)) { manager.matchName = match.name; manager.matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, manager.OnMatchJoined); } ypos += spacing; } if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Back to Match Menu")) { manager.matches = null; } ypos += spacing; } } if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Change MM server")) { m_ShowServer = !m_ShowServer; } if (m_ShowServer) { ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 100 * scale_factor, 20 * scale_factor), "Local")) { manager.SetMatchHost("localhost", 1337, false); m_ShowServer = false; } ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 100 * scale_factor, 20 * scale_factor), "Internet")) { manager.SetMatchHost("mm.unet.unity3d.com", 443, true); m_ShowServer = false; } ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 100 * scale_factor, 20 * scale_factor), "Staging")) { manager.SetMatchHost("staging-mm.unet.unity3d.com", 443, true); m_ShowServer = false; } } ypos += spacing; GUI.Label(new Rect(xpos, ypos, 300 * scale_factor, 20 * scale_factor), "MM Uri: " + manager.matchMaker.baseUri); ypos += spacing; if (GUI.Button(new Rect(xpos, ypos, 200 * scale_factor, 20 * scale_factor), "Disable Match Maker")) { manager.StopMatchMaker(); } ypos += spacing; } } }
internal void RegisterSystemHandlers(bool localClient) { this.RegisterHandlerSafe(11, new NetworkMessageDelegate(this.OnPeerInfo)); ClientScene.RegisterSystemHandlers(this, localClient); this.RegisterHandlerSafe(14, new NetworkMessageDelegate(this.OnCRC)); }
private static void OnObjectDestroy(NetworkMessage netMsg) { netMsg.ReadMessage <ObjectDestroyMessage>(ClientScene.s_ObjectDestroyMessage); if (LogFilter.logDebug) { Debug.Log((object)("ClientScene::OnObjDestroy netId:" + (object)ClientScene.s_ObjectDestroyMessage.netId)); } NetworkIdentity uv; if (ClientScene.s_NetworkScene.GetNetworkIdentity(ClientScene.s_ObjectDestroyMessage.netId, out uv)) { NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, (short)1, ClientScene.GetStringForAssetId(uv.assetId), 1); uv.OnNetworkDestroy(); if (!NetworkScene.InvokeUnSpawnHandler(uv.assetId, uv.gameObject)) { if (uv.sceneId.IsEmpty()) { Object.Destroy((Object)uv.gameObject); } else { uv.gameObject.SetActive(false); ClientScene.s_SpawnableObjects[uv.sceneId] = uv; } } ClientScene.s_NetworkScene.RemoveLocalObject(ClientScene.s_ObjectDestroyMessage.netId); } else { if (!LogFilter.logDebug) { return; } Debug.LogWarning((object)("Did not find target for destroy message for " + (object)ClientScene.s_ObjectDestroyMessage.netId)); } }
// received on both host and clients void OnPeerClientAuthority(NetworkMessage netMsg) { var msg = netMsg.ReadMessage <PeerAuthorityMessage>(); if (LogFilter.logDebug) { Debug.Log("OnPeerClientAuthority for netId:" + msg.netId); } if (m_Peers == null) { // havent received peers yet. just ignore this. the peer list will contain this data. return; } // find the peer for connId for (int peerId = 0; peerId < m_Peers.Length; peerId++) { var p = m_Peers[peerId]; if (p.connectionId == msg.connectionId) { if (p.playerIds == null) { p.playerIds = new PeerInfoPlayer[0]; } if (msg.authorityState) { for (int i = 0; i < p.playerIds.Length; i++) { if (p.playerIds[i].netId == msg.netId) { // already in list return; } } var newPlayerId = new PeerInfoPlayer(); newPlayerId.netId = msg.netId; newPlayerId.playerControllerId = -1; var pl = new List <PeerInfoPlayer>(p.playerIds); pl.Add(newPlayerId); p.playerIds = pl.ToArray(); } else { for (int i = 0; i < p.playerIds.Length; i++) { if (p.playerIds[i].netId == msg.netId) { var pl = new List <PeerInfoPlayer>(p.playerIds); pl.RemoveAt(i); p.playerIds = pl.ToArray(); break; } } } } } var foundObj = ClientScene.FindLocalObject(msg.netId); OnAuthorityUpdated(foundObj, msg.connectionId, msg.authorityState); }
internal void RegisterSystemHandlers(bool localClient) { ClientScene.RegisterSystemHandlers(this, localClient); RegisterHandlerSafe(MsgType.CRC, OnCRC); RegisterHandlerSafe(MsgType.Fragment, NetworkConnection.OnFragment); }
/// <summary> /// <para>This adds a player object for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer will be called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message.</para> /// </summary> /// <param name="readyConn">The connection to become ready for this client.</param> /// <param name="playerControllerId">The local player ID number.</param> /// <param name="extraMessage">An extra message object that can be passed to the server for this player.</param> /// <returns> /// <para>True if player was added.</para> /// </returns> public static bool AddPlayer(NetworkConnection readyConn, short playerControllerId, MessageBase extraMessage) { if ((int)playerControllerId < 0) { if (LogFilter.logError) { Debug.LogError((object)("ClientScene::AddPlayer: playerControllerId of " + (object)playerControllerId + " is negative")); } return(false); } if ((int)playerControllerId > 32) { if (LogFilter.logError) { Debug.LogError((object)("ClientScene::AddPlayer: playerControllerId of " + (object)playerControllerId + " is too high, max is " + (object)32)); } return(false); } if ((int)playerControllerId > 16 && LogFilter.logWarn) { Debug.LogWarning((object)("ClientScene::AddPlayer: playerControllerId of " + (object)playerControllerId + " is unusually high")); } while ((int)playerControllerId >= ClientScene.s_LocalPlayers.Count) { ClientScene.s_LocalPlayers.Add(new PlayerController()); } if (readyConn == null) { if (!ClientScene.s_IsReady) { if (LogFilter.logError) { Debug.LogError((object)"Must call AddPlayer() with a connection the first time to become ready."); } return(false); } } else { ClientScene.s_IsReady = true; ClientScene.s_ReadyConnection = readyConn; } PlayerController playerController; if (ClientScene.s_ReadyConnection.GetPlayerController(playerControllerId, out playerController) && playerController.IsValid && (Object)playerController.gameObject != (Object)null) { if (LogFilter.logError) { Debug.LogError((object)("ClientScene::AddPlayer: playerControllerId of " + (object)playerControllerId + " already in use.")); } return(false); } if (LogFilter.logDebug) { Debug.Log((object)("ClientScene::AddPlayer() for ID " + (object)playerControllerId + " called with connection [" + (object)ClientScene.s_ReadyConnection + "]")); } if (ClientScene.s_ReconnectId == -1) { AddPlayerMessage addPlayerMessage = new AddPlayerMessage(); addPlayerMessage.playerControllerId = playerControllerId; if (extraMessage != null) { NetworkWriter writer = new NetworkWriter(); extraMessage.Serialize(writer); addPlayerMessage.msgData = writer.ToArray(); addPlayerMessage.msgSize = (int)writer.Position; } ClientScene.s_ReadyConnection.Send((short)37, (MessageBase)addPlayerMessage); } else { if (LogFilter.logDebug) { Debug.Log((object)("ClientScene::AddPlayer reconnect " + (object)ClientScene.s_ReconnectId)); } if (ClientScene.s_Peers == null) { ClientScene.SetReconnectId(-1, (PeerInfoMessage[])null); if (LogFilter.logError) { Debug.LogError((object)"ClientScene::AddPlayer: reconnecting, but no peers."); } return(false); } foreach (PeerInfoMessage peer in ClientScene.s_Peers) { if (peer.playerIds != null && peer.connectionId == ClientScene.s_ReconnectId) { foreach (PeerInfoPlayer playerId in peer.playerIds) { ReconnectMessage reconnectMessage = new ReconnectMessage(); reconnectMessage.oldConnectionId = ClientScene.s_ReconnectId; reconnectMessage.netId = playerId.netId; reconnectMessage.playerControllerId = playerId.playerControllerId; if (extraMessage != null) { NetworkWriter writer = new NetworkWriter(); extraMessage.Serialize(writer); reconnectMessage.msgData = writer.ToArray(); reconnectMessage.msgSize = (int)writer.Position; } ClientScene.s_ReadyConnection.Send((short)47, (MessageBase)reconnectMessage); } } } ClientScene.SetReconnectId(-1, (PeerInfoMessage[])null); } return(true); }
private static void OnObjectSpawn(NetworkMessage netMsg) { netMsg.ReadMessage <ObjectSpawnMessage>(ClientScene.s_ObjectSpawnMessage); if (!ClientScene.s_ObjectSpawnMessage.assetId.IsValid()) { if (LogFilter.logError) { Debug.LogError("OnObjSpawn netId: " + ClientScene.s_ObjectSpawnMessage.netId + " has invalid asset Id"); } } else { if (LogFilter.logDebug) { Debug.Log(string.Concat(new object[] { "Client spawn handler instantiating [netId:", ClientScene.s_ObjectSpawnMessage.netId, " asset ID:", ClientScene.s_ObjectSpawnMessage.assetId, " pos:", ClientScene.s_ObjectSpawnMessage.position, "]" })); } NetworkIdentity component; GameObject original; SpawnDelegate spawnDelegate; if (ClientScene.s_NetworkScene.GetNetworkIdentity(ClientScene.s_ObjectSpawnMessage.netId, out component)) { ClientScene.ApplySpawnPayload(component, ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.payload, ClientScene.s_ObjectSpawnMessage.netId, null); } else if (NetworkScene.GetPrefab(ClientScene.s_ObjectSpawnMessage.assetId, out original)) { GameObject gameObject = Object.Instantiate <GameObject>(original, ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.rotation); if (LogFilter.logDebug) { Debug.Log(string.Concat(new object[] { "Client spawn handler instantiating [netId:", ClientScene.s_ObjectSpawnMessage.netId, " asset ID:", ClientScene.s_ObjectSpawnMessage.assetId, " pos:", ClientScene.s_ObjectSpawnMessage.position, " rotation: ", ClientScene.s_ObjectSpawnMessage.rotation, "]" })); } component = gameObject.GetComponent <NetworkIdentity>(); if (component == null) { if (LogFilter.logError) { Debug.LogError("Client object spawned for " + ClientScene.s_ObjectSpawnMessage.assetId + " does not have a NetworkIdentity"); } } else { component.Reset(); ClientScene.ApplySpawnPayload(component, ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.payload, ClientScene.s_ObjectSpawnMessage.netId, gameObject); } } else if (NetworkScene.GetSpawnHandler(ClientScene.s_ObjectSpawnMessage.assetId, out spawnDelegate)) { GameObject gameObject2 = spawnDelegate(ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.assetId); if (gameObject2 == null) { if (LogFilter.logWarn) { Debug.LogWarning("Client spawn handler for " + ClientScene.s_ObjectSpawnMessage.assetId + " returned null"); } } else { component = gameObject2.GetComponent <NetworkIdentity>(); if (component == null) { if (LogFilter.logError) { Debug.LogError("Client object spawned for " + ClientScene.s_ObjectSpawnMessage.assetId + " does not have a network identity"); } } else { component.Reset(); component.SetDynamicAssetId(ClientScene.s_ObjectSpawnMessage.assetId); ClientScene.ApplySpawnPayload(component, ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.payload, ClientScene.s_ObjectSpawnMessage.netId, gameObject2); } } } else if (LogFilter.logError) { Debug.LogError(string.Concat(new object[] { "Failed to spawn server object, did you forget to add it to the NetworkManager? assetId=", ClientScene.s_ObjectSpawnMessage.assetId, " netId=", ClientScene.s_ObjectSpawnMessage.netId })); } } }
// ------------------------ optional UI ------------------------ void OnGUI() { if (!ShowLobbyGUI) { return; } var lobby = GetLobbyManager(); if (lobby) { if (!lobby.showLobbyGUI) { return; } string loadedSceneName = SceneManager.GetSceneAt(0).name; if (loadedSceneName != lobby.lobbyScene) { return; } } Rect rec = new Rect(100 + m_Slot * 100, 200, 90, 20); if (isLocalPlayer) { string youStr; if (m_ReadyToBegin) { youStr = "(Ready)"; } else { youStr = "(Not Ready)"; } GUI.Label(rec, youStr); if (m_ReadyToBegin) { rec.y += 25; if (GUI.Button(rec, "STOP")) { SendNotReadyToBeginMessage(); } } else { rec.y += 25; if (GUI.Button(rec, "START")) { SendReadyToBeginMessage(); } rec.y += 25; if (GUI.Button(rec, "Remove")) { ClientScene.RemovePlayer(GetComponent <NetworkIdentity>().playerControllerId); } } } else { GUI.Label(rec, "Player [" + netId + "]"); rec.y += 25; GUI.Label(rec, "Ready [" + m_ReadyToBegin + "]"); } }
public static bool AddPlayer(NetworkConnection readyConn, short playerControllerId, MessageBase extraMessage) { bool result; if (playerControllerId < 0) { if (LogFilter.logError) { Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is negative"); } result = false; } else if (playerControllerId > 32) { if (LogFilter.logError) { Debug.LogError(string.Concat(new object[] { "ClientScene::AddPlayer: playerControllerId of ", playerControllerId, " is too high, max is ", 32 })); } result = false; } else { if (playerControllerId > 16) { if (LogFilter.logWarn) { Debug.LogWarning("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " is unusually high"); } } while ((int)playerControllerId >= ClientScene.s_LocalPlayers.Count) { ClientScene.s_LocalPlayers.Add(new PlayerController()); } if (readyConn == null) { if (!ClientScene.s_IsReady) { if (LogFilter.logError) { Debug.LogError("Must call AddPlayer() with a connection the first time to become ready."); } return(false); } } else { ClientScene.s_IsReady = true; ClientScene.s_ReadyConnection = readyConn; } PlayerController playerController; if (ClientScene.s_ReadyConnection.GetPlayerController(playerControllerId, out playerController)) { if (playerController.IsValid && playerController.gameObject != null) { if (LogFilter.logError) { Debug.LogError("ClientScene::AddPlayer: playerControllerId of " + playerControllerId + " already in use."); } return(false); } } if (LogFilter.logDebug) { Debug.Log(string.Concat(new object[] { "ClientScene::AddPlayer() for ID ", playerControllerId, " called with connection [", ClientScene.s_ReadyConnection, "]" })); } if (!ClientScene.hasMigrationPending()) { AddPlayerMessage addPlayerMessage = new AddPlayerMessage(); addPlayerMessage.playerControllerId = playerControllerId; if (extraMessage != null) { NetworkWriter networkWriter = new NetworkWriter(); extraMessage.Serialize(networkWriter); addPlayerMessage.msgData = networkWriter.ToArray(); addPlayerMessage.msgSize = (int)networkWriter.Position; } ClientScene.s_ReadyConnection.Send(37, addPlayerMessage); result = true; } else { result = ClientScene.SendReconnectMessage(extraMessage); } } return(result); }
public static bool AddPlayer(short playerControllerId) { return(ClientScene.AddPlayer(null, playerControllerId)); }
internal void OnStartServer(bool allowNonZeroNetId) { if (!this.m_IsServer) { this.m_IsServer = true; if (this.m_LocalPlayerAuthority) { this.m_HasAuthority = false; } else { this.m_HasAuthority = true; } this.m_Observers = new List <NetworkConnection>(); this.m_ObserverConnections = new HashSet <int>(); this.CacheBehaviours(); if (this.netId.IsEmpty()) { this.m_NetId = NetworkIdentity.GetNextNetworkId(); } else if (!allowNonZeroNetId) { if (LogFilter.logError) { Debug.LogError(string.Concat(new object[] { "Object has non-zero netId ", this.netId, " for ", base.gameObject })); } return; } if (LogFilter.logDev) { Debug.Log(string.Concat(new object[] { "OnStartServer ", base.gameObject, " GUID:", this.netId })); } NetworkServer.instance.SetLocalObjectOnServer(this.netId, base.gameObject); for (int i = 0; i < this.m_NetworkBehaviours.Length; i++) { NetworkBehaviour networkBehaviour = this.m_NetworkBehaviours[i]; try { networkBehaviour.OnStartServer(); } catch (Exception ex) { Debug.LogError("Exception in OnStartServer:" + ex.Message + " " + ex.StackTrace); } } if (NetworkClient.active && NetworkServer.localClientActive) { ClientScene.SetLocalObject(this.netId, base.gameObject); this.OnStartClient(); } if (this.m_HasAuthority) { this.OnStartAuthority(); } } }
/// <summary> /// <para>This adds a player object for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer will be called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message.</para> /// </summary> /// <param name="readyConn">The connection to become ready for this client.</param> /// <param name="playerControllerId">The local player ID number.</param> /// <param name="extraMessage">An extra message object that can be passed to the server for this player.</param> /// <returns> /// <para>True if player was added.</para> /// </returns> public static bool AddPlayer(short playerControllerId) { return(ClientScene.AddPlayer((NetworkConnection)null, playerControllerId)); }
public bool ReconnectToNewHost(string serverIp, int serverPort) { if (!NetworkClient.active) { if (LogFilter.logError) { Debug.LogError("Reconnect - NetworkClient must be active"); } return(false); } if (m_Connection == null) { if (LogFilter.logError) { Debug.LogError("Reconnect - no old connection exists"); } return(false); } if (LogFilter.logInfo) { Debug.Log("NetworkClient Reconnect " + serverIp + ":" + serverPort); } ClientScene.HandleClientDisconnect(m_Connection); ClientScene.ClearLocalPlayers(); m_Connection.Disconnect(); m_Connection = null; m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); string hostnameOrIp = serverIp; m_ServerPort = serverPort; //TODO: relay reconnect /* * if (Match.NetworkMatch.matchSingleton != null) * { * hostnameOrIp = Match.NetworkMatch.matchSingleton.address; * m_ServerPort = Match.NetworkMatch.matchSingleton.port; * }*/ if (UnityEngine.Application.platform == RuntimePlatform.WebGLPlayer) { m_ServerIp = hostnameOrIp; m_AsyncConnect = ConnectState.Resolved; } else if (serverIp.Equals("127.0.0.1") || serverIp.Equals("localhost")) { m_ServerIp = "127.0.0.1"; m_AsyncConnect = ConnectState.Resolved; } else { if (LogFilter.logDebug) { Debug.Log("Async DNS START:" + hostnameOrIp); } m_AsyncConnect = ConnectState.Resolving; Dns.BeginGetHostAddresses(hostnameOrIp, new AsyncCallback(GetHostAddressesCallback), this); } return(true); }
/// <summary> /// <para>This adds a player object for this client. This causes an AddPlayer message to be sent to the server, and NetworkManager.OnServerAddPlayer will be called. If an extra message was passed to AddPlayer, then OnServerAddPlayer will be called with a NetworkReader that contains the contents of the message.</para> /// </summary> /// <param name="readyConn">The connection to become ready for this client.</param> /// <param name="playerControllerId">The local player ID number.</param> /// <param name="extraMessage">An extra message object that can be passed to the server for this player.</param> /// <returns> /// <para>True if player was added.</para> /// </returns> public static bool AddPlayer(NetworkConnection readyConn, short playerControllerId) { return(ClientScene.AddPlayer(readyConn, playerControllerId, (MessageBase)null)); }
public bool ReconnectToNewHost(EndPoint secureTunnelEndPoint) { if (!NetworkClient.active) { if (LogFilter.logError) { Debug.LogError("Reconnect - NetworkClient must be active"); } return(false); } if (m_Connection == null) { if (LogFilter.logError) { Debug.LogError("Reconnect - no old connection exists"); } return(false); } if (LogFilter.logInfo) { Debug.Log("NetworkClient Reconnect to remoteSockAddr"); } ClientScene.HandleClientDisconnect(m_Connection); ClientScene.ClearLocalPlayers(); m_Connection.Disconnect(); m_Connection = null; m_ClientId = NetworkTransport.AddHost(m_HostTopology, m_HostPort); if (secureTunnelEndPoint == null) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: null endpoint passed in"); } m_AsyncConnect = ConnectState.Failed; return(false); } // Make sure it's either IPv4 or IPv6 if (secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetwork && secureTunnelEndPoint.AddressFamily != AddressFamily.InterNetworkV6) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: Endpoint AddressFamily must be either InterNetwork or InterNetworkV6"); } m_AsyncConnect = ConnectState.Failed; return(false); } // Make sure it's an Endpoint we know what to do with string endPointType = secureTunnelEndPoint.GetType().FullName; if (endPointType == "System.Net.IPEndPoint") { IPEndPoint tmp = (IPEndPoint)secureTunnelEndPoint; Connect(tmp.Address.ToString(), tmp.Port); return(m_AsyncConnect != ConnectState.Failed); } if ((endPointType != "UnityEngine.XboxOne.XboxOneEndPoint") && (endPointType != "UnityEngine.PS4.SceEndPoint")) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: invalid Endpoint (not IPEndPoint or XboxOneEndPoint or SceEndPoint)"); } m_AsyncConnect = ConnectState.Failed; return(false); } byte error = 0; // regular non-relay connect m_RemoteEndPoint = secureTunnelEndPoint; m_AsyncConnect = ConnectState.Connecting; try { m_ClientConnectionId = NetworkTransport.ConnectEndPoint(m_ClientId, m_RemoteEndPoint, 0, out error); } catch (Exception ex) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: Exception when trying to connect to EndPoint: " + ex); } m_AsyncConnect = ConnectState.Failed; return(false); } if (m_ClientConnectionId == 0) { if (LogFilter.logError) { Debug.LogError("Reconnect failed: Unable to connect to EndPoint (" + error + ")"); } m_AsyncConnect = ConnectState.Failed; return(false); } m_Connection = (NetworkConnection)Activator.CreateInstance(m_NetworkConnectionClass); m_Connection.SetHandlers(m_MessageHandlers); m_Connection.Initialize(m_ServerIp, m_ClientId, m_ClientConnectionId, m_HostTopology); return(true); }
private static void OnObjectSpawn(NetworkMessage netMsg) { netMsg.ReadMessage <ObjectSpawnMessage>(ClientScene.s_ObjectSpawnMessage); if (!ClientScene.s_ObjectSpawnMessage.assetId.IsValid()) { if (!LogFilter.logError) { return; } Debug.LogError((object)("OnObjSpawn netId: " + (object)ClientScene.s_ObjectSpawnMessage.netId + " has invalid asset Id")); } else { if (LogFilter.logDebug) { Debug.Log((object)("Client spawn handler instantiating [netId:" + (object)ClientScene.s_ObjectSpawnMessage.netId + " asset ID:" + (object)ClientScene.s_ObjectSpawnMessage.assetId + " pos:" + (object)ClientScene.s_ObjectSpawnMessage.position + "]")); } NetworkDetailStats.IncrementStat(NetworkDetailStats.NetworkDirection.Incoming, (short)3, ClientScene.GetStringForAssetId(ClientScene.s_ObjectSpawnMessage.assetId), 1); NetworkIdentity uv; if (ClientScene.s_NetworkScene.GetNetworkIdentity(ClientScene.s_ObjectSpawnMessage.netId, out uv)) { ClientScene.ApplySpawnPayload(uv, ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.payload, ClientScene.s_ObjectSpawnMessage.netId, (GameObject)null); } else { GameObject prefab; if (NetworkScene.GetPrefab(ClientScene.s_ObjectSpawnMessage.assetId, out prefab)) { GameObject newGameObject = (GameObject)Object.Instantiate((Object)prefab, ClientScene.s_ObjectSpawnMessage.position, Quaternion.identity); uv = newGameObject.GetComponent <NetworkIdentity>(); if ((Object)uv == (Object)null) { if (!LogFilter.logError) { return; } Debug.LogError((object)("Client object spawned for " + (object)ClientScene.s_ObjectSpawnMessage.assetId + " does not have a NetworkIdentity")); } else { ClientScene.ApplySpawnPayload(uv, ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.payload, ClientScene.s_ObjectSpawnMessage.netId, newGameObject); } } else { SpawnDelegate handler; if (NetworkScene.GetSpawnHandler(ClientScene.s_ObjectSpawnMessage.assetId, out handler)) { GameObject newGameObject = handler(ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.assetId); if ((Object)newGameObject == (Object)null) { if (!LogFilter.logWarn) { return; } Debug.LogWarning((object)("Client spawn handler for " + (object)ClientScene.s_ObjectSpawnMessage.assetId + " returned null")); } else { uv = newGameObject.GetComponent <NetworkIdentity>(); if ((Object)uv == (Object)null) { if (!LogFilter.logError) { return; } Debug.LogError((object)("Client object spawned for " + (object)ClientScene.s_ObjectSpawnMessage.assetId + " does not have a network identity")); } else { uv.SetDynamicAssetId(ClientScene.s_ObjectSpawnMessage.assetId); ClientScene.ApplySpawnPayload(uv, ClientScene.s_ObjectSpawnMessage.position, ClientScene.s_ObjectSpawnMessage.payload, ClientScene.s_ObjectSpawnMessage.netId, newGameObject); } } } else { if (!LogFilter.logError) { return; } Debug.LogError((object)("Failed to spawn server object, assetId=" + (object)ClientScene.s_ObjectSpawnMessage.assetId + " netId=" + (object)ClientScene.s_ObjectSpawnMessage.netId)); } } } } }
internal virtual void Update() { if (m_ClientId == -1) { return; } switch (m_AsyncConnect) { case ConnectState.None: case ConnectState.Resolving: case ConnectState.Disconnected: return; case ConnectState.Failed: GenerateConnectError((int)NetworkError.DNSFailure); m_AsyncConnect = ConnectState.Disconnected; return; case ConnectState.Resolved: m_AsyncConnect = ConnectState.Connecting; ContinueConnect(); return; case ConnectState.Connecting: case ConnectState.Connected: { break; } } if (m_Connection != null) { if ((int)Time.time != m_StatResetTime) { m_Connection.ResetStats(); m_StatResetTime = (int)Time.time; } } int numEvents = 0; NetworkEventType networkEvent; do { int connectionId; int channelId; int receivedSize; byte error; networkEvent = NetworkTransport.ReceiveFromHost(m_ClientId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error); if (m_Connection != null) { m_Connection.lastError = (NetworkError)error; } if (networkEvent != NetworkEventType.Nothing) { if (LogFilter.logDev) { Debug.Log("Client event: host=" + m_ClientId + " event=" + networkEvent + " error=" + error); } } switch (networkEvent) { case NetworkEventType.ConnectEvent: if (LogFilter.logDebug) { Debug.Log("Client connected"); } if (error != 0) { GenerateConnectError(error); return; } m_AsyncConnect = ConnectState.Connected; m_Connection.InvokeHandlerNoData(MsgType.Connect); break; case NetworkEventType.DataEvent: if (error != 0) { GenerateDataError(error); return; } #if UNITY_EDITOR UnityEditor.NetworkDetailStats.IncrementStat( UnityEditor.NetworkDetailStats.NetworkDirection.Incoming, MsgType.LLAPIMsg, "msg", 1); #endif m_MsgReader.SeekZero(); m_Connection.TransportReceive(m_MsgBuffer, receivedSize, channelId); break; case NetworkEventType.DisconnectEvent: if (LogFilter.logDebug) { Debug.Log("Client disconnected"); } m_AsyncConnect = ConnectState.Disconnected; if (error != 0) { if ((NetworkError)error != NetworkError.Timeout) { GenerateDisconnectError(error); } } ClientScene.HandleClientDisconnect(m_Connection); if (m_Connection != null) { m_Connection.InvokeHandlerNoData(MsgType.Disconnect); } break; case NetworkEventType.Nothing: break; default: if (LogFilter.logError) { Debug.LogError("Unknown network message type received: " + networkEvent); } break; } if (++numEvents >= k_MaxEventsPerFrame) { if (LogFilter.logDebug) { Debug.Log("MaxEventsPerFrame hit (" + k_MaxEventsPerFrame + ")"); } break; } if (m_ClientId == -1) { break; } }while (networkEvent != NetworkEventType.Nothing); if (m_Connection != null && m_AsyncConnect == ConnectState.Connected) { m_Connection.FlushChannels(); } }
void OnGUI() { if (!showGUI) { return; } bool noConnection = (manager.client == null || manager.client.connection == null || manager.client.connection.connectionId == -1); GUILayout.BeginArea(new Rect(10 + offsetX, 40 + offsetY, 215, 9999)); if (!manager.IsClientConnected() && !NetworkServer.active) { if (noConnection) { // LAN Host if (Application.platform != RuntimePlatform.WebGLPlayer) { if (GUILayout.Button("LAN Host")) { manager.StartHost(); } } // LAN Client + IP GUILayout.BeginHorizontal(); if (GUILayout.Button("LAN Client")) { manager.StartClient(); } manager.networkAddress = GUILayout.TextField(manager.networkAddress); GUILayout.EndHorizontal(); // LAN Server Only if (Application.platform == RuntimePlatform.WebGLPlayer) { // cant be a server in webgl build GUILayout.Box("( WebGL cannot be server )"); } else { if (GUILayout.Button("LAN Server Only")) { manager.StartServer(); } } } else { // Connecting GUILayout.Label("Connecting to " + manager.networkAddress + ":" + manager.networkPort + ".."); if (GUILayout.Button("Cancel Connection Attempt")) { manager.StopClient(); } } } else { // server / client status message if (NetworkServer.active) { string serverMsg = "Server: port=" + manager.networkPort; if (manager.useWebSockets) { serverMsg += " (Using WebSockets)"; } GUILayout.Label(serverMsg); } if (manager.IsClientConnected()) { GUILayout.Label("Client: address=" + manager.networkAddress + " port=" + manager.networkPort); } } // client ready if (manager.IsClientConnected() && !ClientScene.ready) { if (GUILayout.Button("Client Ready")) { ClientScene.Ready(manager.client.connection); if (ClientScene.localPlayers.Count == 0) { ClientScene.AddPlayer(0); } } } // stop if (NetworkServer.active || manager.IsClientConnected()) { if (GUILayout.Button("Stop")) { manager.StopHost(); } } GUILayout.EndArea(); }
internal void OnStartServer(bool allowNonZeroNetId) { if (m_IsServer) { return; } m_IsServer = true; if (m_LocalPlayerAuthority) { // local player on server has NO authority m_HasAuthority = false; } else { // enemy on server has authority m_HasAuthority = true; } m_Observers = new List <NetworkConnection>(); m_ObserverConnections = new HashSet <int>(); CacheBehaviours(); // If the instance/net ID is invalid here then this is an object instantiated from a prefab and the server should assign a valid ID if (netId.IsEmpty()) { m_NetId = GetNextNetworkId(); } else { if (allowNonZeroNetId) { //allowed } else { if (LogFilter.logError) { Debug.LogError("Object has non-zero netId " + netId + " for " + gameObject); } return; } } if (LogFilter.logDev) { Debug.Log("OnStartServer " + gameObject + " GUID:" + netId); } NetworkServer.instance.SetLocalObjectOnServer(netId, gameObject); for (int i = 0; i < m_NetworkBehaviours.Length; i++) { NetworkBehaviour comp = m_NetworkBehaviours[i]; try { comp.OnStartServer(); } catch (Exception e) { Debug.LogError("Exception in OnStartServer:" + e.Message + " " + e.StackTrace); } } if (NetworkClient.active && NetworkServer.localClientActive) { // there will be no spawn message, so start the client here too ClientScene.SetLocalObject(netId, gameObject); OnStartClient(); } if (m_HasAuthority) { OnStartAuthority(); } }
void Update() { if ((gameTime % 3600) / 60 > 9) { gameTimerText.text = gameTime / 3600 + ":" + (gameTime % 3600) / 60; } else { gameTimerText.text = gameTime / 3600 + ":0" + (gameTime % 3600) / 60; } if (gameTime <= 0) { scores.Clear(); ending = true; if (winner != null) { Destroy(winner.gameObject); } winner = (Text)Instantiate(whoWon, whoWon.transform.position, whoWon.transform.rotation); winner.enabled = true; winner.gameObject.SetActive(true); winner.transform.SetParent(whoWon.transform.parent); try { for (int i = 0; i < playerKills.Count; i++) { ((Text)playerDeaths[i]).text = (ClientScene.FindLocalObject((NetworkInstanceId)playerNetIDs[i]).GetComponent <PlayerSetup>().deaths).ToString(); ((Text)playerKills[i]).text = (ClientScene.FindLocalObject((NetworkInstanceId)playerNetIDs[i]).GetComponent <PlayerSetup>().kills).ToString(); scores.Add(int.Parse(((Text)playerKills[i]).text) - int.Parse(((Text)playerDeaths[i]).text)); } } catch (Exception e) { disconnect(); } int indexOfWinner = 0; for (int i = 0; i < scores.Count; i++) { if ((int)scores[i] > (int)scores[indexOfWinner]) { indexOfWinner = i; } } winner.text = (string)playerNames[indexOfWinner] + " has won with a score of " + ((Text)playerKills[indexOfWinner]).text + " and " + ((Text)playerDeaths[indexOfWinner]).text; if (gameTime < -180) { disconnect(); } } GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); if (players.Length != playerNames.Count) { playerNames.Clear(); playerNetIDs.Clear(); for (int i = 0; i < playersInGame.Count; i++) { Destroy((Text)playersInGame[i]); Destroy((Text)playerDeaths[i]); Destroy((Text)playerKills[i]); } playerDeaths.Clear(); playerKills.Clear(); playersInGame.Clear(); for (int i = 0; i < players.Length; i++) { if (players[i].GetComponent <PlayerSetup>().playerName != "") { playerNames.Add(players[i].GetComponent <PlayerSetup>().playerName); playerNetIDs.Add(players[i].GetComponent <NetworkIdentity>().netId); print(playerNames[i]); playersInGame.Add((Text)Instantiate(playerHeading, new Vector3(playerHeading.transform.position.x, playerHeading.transform.position.y + (i + 1) * -35, 0), playerHeading.transform.rotation)); ((Text)playersInGame[i]).transform.SetParent(leaderboardPanel.transform); ((Text)playersInGame[i]).text = (string)playerNames[i]; playerKills.Add((Text)Instantiate(killHeading, new Vector3(killHeading.transform.position.x, killHeading.transform.position.y + (i + 1) * -35, 0), killHeading.transform.rotation)); ((Text)playerKills[i]).transform.SetParent(leaderboardPanel.transform); ((Text)playerKills[i]).text = (ClientScene.FindLocalObject((NetworkInstanceId)playerNetIDs[i]).GetComponent <PlayerSetup>().kills).ToString(); playerDeaths.Add((Text)Instantiate(deathHeading, new Vector3(deathHeading.transform.position.x, deathHeading.transform.position.y + (i + 1) * -35, 0), deathHeading.transform.rotation)); ((Text)playerDeaths[i]).transform.SetParent(leaderboardPanel.transform); ((Text)playerDeaths[i]).text = (ClientScene.FindLocalObject((NetworkInstanceId)playerNetIDs[i]).GetComponent <PlayerSetup>().deaths).ToString(); } } } if (!showGUI) { return; } if (Input.GetButtonDown("Pause") && ((NetworkClient.active && manager.IsClientConnected()) || NetworkServer.active /*manager.matchMaker != null*/) && !ending) { pausePanel.SetActive(!pausePanel.activeSelf); } if (Input.GetButton("Leaderboards") && ((NetworkClient.active && manager.IsClientConnected()) || NetworkServer.active /*manager.matchMaker != null*/) && !ending) { for (int i = 0; i < playerKills.Count; i++) { ((Text)playerDeaths[i]).text = (ClientScene.FindLocalObject((NetworkInstanceId)playerNetIDs[i]).GetComponent <PlayerSetup>().deaths).ToString(); ((Text)playerKills[i]).text = (ClientScene.FindLocalObject((NetworkInstanceId)playerNetIDs[i]).GetComponent <PlayerSetup>().kills).ToString(); } leaderboardPanel.SetActive(true); } else { leaderboardPanel.SetActive(false); } if (!NetworkClient.active && !NetworkServer.active /*manager.matchMaker == null*/) { if (winner != null) { Destroy(winner.gameObject); } ending = false; gameTime = originalGameTime; if (playerNames.Count > 0) { playerNames.Clear(); for (int i = 0; i < playersInGame.Count; i++) { Destroy((Text)playersInGame[i]); Destroy((Text)playerDeaths[i]); Destroy((Text)playerKills[i]); } playerDeaths.Clear(); playerKills.Clear(); playersInGame.Clear(); } leaderboardPanel.SetActive(false); pausePanel.SetActive(false); panelToToggleActive.SetActive(true); configPanel.SetActive(true); connectingPanel.SetActive(false); } if ((NetworkClient.active && manager.IsClientConnected()) || NetworkServer.active /*manager.matchMaker != null*/) { panelToToggleActive.SetActive(false); } else { panelToToggleActive.SetActive(true); } if (!manager.IsClientConnected() && NetworkClient.active) { connectingPanel.SetActive(true); configPanel.SetActive(false); attemptingConnect.GetComponent <Text>().text = "Attempting to Connect to " + manager.networkAddress; } }
internal virtual void Update() { if (m_ClientId == -1) { return; } switch (m_AsyncConnect) { case ConnectState.None: case ConnectState.Resolving: case ConnectState.Disconnected: return; case ConnectState.Failed: GenerateConnectError((int)NetworkError.DNSFailure); m_AsyncConnect = ConnectState.Disconnected; return; case ConnectState.Resolved: m_AsyncConnect = ConnectState.Connecting; ContinueConnect(); return; case ConnectState.Connecting: case ConnectState.Connected: { break; } } int numEvents = 0; NetworkEventType networkEvent; do { int connectionId; int channelId; int receivedSize; byte error; networkEvent = NetworkTransport.ReceiveFromHost(m_ClientId, out connectionId, out channelId, m_MsgBuffer, (ushort)m_MsgBuffer.Length, out receivedSize, out error); if (m_Connection != null) { m_Connection.lastError = (NetworkError)error; } if (networkEvent != NetworkEventType.Nothing) { if (LogFilter.logDev) { Debug.Log("Client event: host=" + m_ClientId + " event=" + networkEvent + " error=" + error); } } switch (networkEvent) { case NetworkEventType.ConnectEvent: if (LogFilter.logDebug) { Debug.Log("Client connected"); } if (error != 0) { GenerateConnectError(error); return; } m_AsyncConnect = ConnectState.Connected; m_Connection.InvokeHandlerNoData((short)MsgType.Connect); break; case NetworkEventType.DataEvent: if (error != 0) { GenerateDataError(error); return; } #if UNITY_EDITOR UnityEditor.NetworkDetailStats.IncrementStat( UnityEditor.NetworkDetailStats.NetworkDirection.Incoming, (short)MsgType.LLAPIMsg, "msg", 1); #endif // create a buffer with exactly 'receivedSize' size for the handlers so we don't need to read // a size header (saves bandwidth) byte[] data = new byte[receivedSize]; Array.Copy(m_MsgBuffer, data, receivedSize); m_Connection.TransportReceive(data, channelId); break; case NetworkEventType.DisconnectEvent: if (LogFilter.logDebug) { Debug.Log("Client disconnected"); } m_AsyncConnect = ConnectState.Disconnected; if (error != 0) { if ((NetworkError)error != NetworkError.Timeout) { GenerateDisconnectError(error); } } ClientScene.HandleClientDisconnect(m_Connection); if (m_Connection != null) { m_Connection.InvokeHandlerNoData((short)MsgType.Disconnect); } break; case NetworkEventType.Nothing: break; default: if (LogFilter.logError) { Debug.LogError("Unknown network message type received: " + networkEvent); } break; } if (++numEvents >= k_MaxEventsPerFrame) { if (LogFilter.logDebug) { Debug.Log("MaxEventsPerFrame hit (" + k_MaxEventsPerFrame + ")"); } break; } if (m_ClientId == -1) { break; } }while (networkEvent != NetworkEventType.Nothing); }
private void OnGUI() { if (!this.showGUI) { return; } int num = 10 + this.offsetX; int num2 = 40 + this.offsetY; bool flag = this.manager.client == null || this.manager.client.connection == null || this.manager.client.connection.connectionId == -1; if (!this.manager.IsClientConnected() && !NetworkServer.active && this.manager.matchMaker == null) { if (flag) { if (Application.platform != RuntimePlatform.WebGLPlayer) { if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "LAN Host(H)")) { this.manager.StartHost(); } num2 += 24; } if (GUI.Button(new Rect((float)num, (float)num2, 105f, 20f), "LAN Client(C)")) { this.manager.StartClient(); } this.manager.networkAddress = GUI.TextField(new Rect((float)(num + 100), (float)num2, 95f, 20f), this.manager.networkAddress); num2 += 24; if (Application.platform == RuntimePlatform.WebGLPlayer) { GUI.Box(new Rect((float)num, (float)num2, 200f, 25f), "( WebGL cannot be server )"); num2 += 24; } else { if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "LAN Server Only(S)")) { this.manager.StartServer(); } num2 += 24; } } else { GUI.Label(new Rect((float)num, (float)num2, 200f, 20f), string.Concat(new object[] { "Connecting to ", this.manager.networkAddress, ":", this.manager.networkPort, ".." })); num2 += 24; if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Cancel Connection Attempt")) { this.manager.StopClient(); } } } else { if (NetworkServer.active) { string text = "Server: port=" + this.manager.networkPort; if (this.manager.useWebSockets) { text += " (Using WebSockets)"; } GUI.Label(new Rect((float)num, (float)num2, 300f, 20f), text); num2 += 24; } if (this.manager.IsClientConnected()) { GUI.Label(new Rect((float)num, (float)num2, 300f, 20f), string.Concat(new object[] { "Client: address=", this.manager.networkAddress, " port=", this.manager.networkPort })); num2 += 24; } } if (this.manager.IsClientConnected() && !ClientScene.ready) { if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Client Ready")) { ClientScene.Ready(this.manager.client.connection); if (ClientScene.localPlayers.Count == 0) { ClientScene.AddPlayer(0); } } num2 += 24; } if (NetworkServer.active || this.manager.IsClientConnected()) { if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Stop (X)")) { this.manager.StopHost(); } num2 += 24; } if (!NetworkServer.active && !this.manager.IsClientConnected() && flag) { num2 += 10; if (Application.platform == RuntimePlatform.WebGLPlayer) { GUI.Box(new Rect((float)(num - 5), (float)num2, 220f, 25f), "(WebGL cannot use Match Maker)"); return; } if (this.manager.matchMaker == null) { if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Enable Match Maker (M)")) { this.manager.StartMatchMaker(); } num2 += 24; } else { if (this.manager.matchInfo == null) { if (this.manager.matches == null) { if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Create Internet Match")) { this.manager.matchMaker.CreateMatch(this.manager.matchName, this.manager.matchSize, true, string.Empty, string.Empty, string.Empty, 0, 0, new NetworkMatch.DataResponseDelegate <MatchInfo>(this.manager.OnMatchCreate)); } num2 += 24; GUI.Label(new Rect((float)num, (float)num2, 100f, 20f), "Room Name:"); this.manager.matchName = GUI.TextField(new Rect((float)(num + 100), (float)num2, 100f, 20f), this.manager.matchName); num2 += 24; num2 += 10; if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Find Internet Match")) { this.manager.matchMaker.ListMatches(0, 20, string.Empty, false, 0, 0, new NetworkMatch.DataResponseDelegate <List <MatchInfoSnapshot> >(this.manager.OnMatchList)); } num2 += 24; } else { for (int i = 0; i < this.manager.matches.Count; i++) { MatchInfoSnapshot matchInfoSnapshot = this.manager.matches[i]; if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Join Match:" + matchInfoSnapshot.name)) { this.manager.matchName = matchInfoSnapshot.name; this.manager.matchMaker.JoinMatch(matchInfoSnapshot.networkId, string.Empty, string.Empty, string.Empty, 0, 0, new NetworkMatch.DataResponseDelegate <MatchInfo>(this.manager.OnMatchJoined)); } num2 += 24; } if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Back to Match Menu")) { this.manager.matches = null; } num2 += 24; } } if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Change MM server")) { this.m_ShowServer = !this.m_ShowServer; } if (this.m_ShowServer) { num2 += 24; if (GUI.Button(new Rect((float)num, (float)num2, 100f, 20f), "Local")) { this.manager.SetMatchHost("localhost", 1337, false); this.m_ShowServer = false; } num2 += 24; if (GUI.Button(new Rect((float)num, (float)num2, 100f, 20f), "Internet")) { this.manager.SetMatchHost("mm.unet.unity3d.com", 443, true); this.m_ShowServer = false; } num2 += 24; if (GUI.Button(new Rect((float)num, (float)num2, 100f, 20f), "Staging")) { this.manager.SetMatchHost("staging-mm.unet.unity3d.com", 443, true); this.m_ShowServer = false; } } num2 += 24; GUI.Label(new Rect((float)num, (float)num2, 300f, 20f), "MM Uri: " + this.manager.matchMaker.baseUri); num2 += 24; if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Disable Match Maker")) { this.manager.StopMatchMaker(); } num2 += 24; } } }
internal virtual void Update() { if (this.m_ClientId == -1) { return; } switch (this.m_AsyncConnect) { case NetworkClient.ConnectState.None: case NetworkClient.ConnectState.Resolving: case NetworkClient.ConnectState.Disconnected: return; case NetworkClient.ConnectState.Resolved: this.m_AsyncConnect = NetworkClient.ConnectState.Connecting; this.ContinueConnect(); return; case NetworkClient.ConnectState.Failed: this.GenerateConnectError(11); this.m_AsyncConnect = NetworkClient.ConnectState.Disconnected; return; } if (this.m_Connection != null && (int)Time.time != this.m_StatResetTime) { this.m_Connection.ResetStats(); this.m_StatResetTime = (int)Time.time; } byte b; while (true) { int num = 0; int num2; int channelId; int numBytes; NetworkEventType networkEventType = NetworkTransport.ReceiveFromHost(this.m_ClientId, out num2, out channelId, this.m_MsgBuffer, (int)((ushort)this.m_MsgBuffer.Length), out numBytes, out b); if (networkEventType != NetworkEventType.Nothing && LogFilter.logDev) { Debug.Log(string.Concat(new object[] { "Client event: host=", this.m_ClientId, " event=", networkEventType, " error=", b })); } switch (networkEventType) { case NetworkEventType.DataEvent: if (b != 0) { goto Block_10; } this.m_MsgReader.SeekZero(); this.m_Connection.TransportRecieve(this.m_MsgBuffer, numBytes, channelId); break; case NetworkEventType.ConnectEvent: if (LogFilter.logDebug) { Debug.Log("Client connected"); } if (b != 0) { goto Block_9; } this.m_AsyncConnect = NetworkClient.ConnectState.Connected; this.m_Connection.InvokeHandlerNoData(32); break; case NetworkEventType.DisconnectEvent: if (LogFilter.logDebug) { Debug.Log("Client disconnected"); } this.m_AsyncConnect = NetworkClient.ConnectState.Disconnected; if (b != 0) { this.GenerateDisconnectError((int)b); } ClientScene.HandleClientDisconnect(this.m_Connection); this.m_Connection.InvokeHandlerNoData(33); break; case NetworkEventType.Nothing: break; default: if (LogFilter.logError) { Debug.LogError("Unknown network message type received: " + networkEventType); } break; } if (num + 1 >= 500) { goto Block_14; } if (this.m_ClientId == -1) { goto Block_16; } if (networkEventType == NetworkEventType.Nothing) { goto IL_26B; } } Block_9: this.GenerateConnectError((int)b); return; Block_10: this.GenerateDataError((int)b); return; Block_14: if (LogFilter.logDebug) { Debug.Log("MaxEventsPerFrame hit (" + 500 + ")"); } Block_16: IL_26B: if (this.m_Connection != null && this.m_AsyncConnect == NetworkClient.ConnectState.Connected) { this.m_Connection.FlushChannels(); } }