private void Update() { //Init some values (first frame only) if (isServer && !isInit) { var identity = GetComponent <NetworkIdentity>(); if (identity.connectionToClient != null) { hostID = identity.connectionToClient.hostId; connID = identity.connectionToClient.connectionId; isInit = true; } } else { isInit = true; } //Update player ping if (isServer && !isLocalPlayer && Time.time > nextUpdate) { nextUpdate = Time.time + GetNetworkSendInterval(); byte error; Ping = (short)NetworkTransport.GetCurrentRTT(hostID, connID, out error); } //TODO remove spawn code if (Input.GetKeyUp(KeyCode.K)) { CmdSpawnPlayer(); } }
/// <summary> /// Get the RTT in seconds for the owner of this network object. Only valid on Server. /// </summary> public float GetRTT() { NetworkConnection conn = NI.clientAuthorityOwner; byte error = 0; return((conn == null || conn.hostId == -1) ? 0 : .001f * NetworkTransport.GetCurrentRTT(NI.clientAuthorityOwner.hostId, NI.clientAuthorityOwner.connectionId, out error)); }
public static void Simulate(int clientId, Action action) { if (!NetworkingManager.singleton.isServer) { Debug.LogWarning("MLAPI: Lag compensation simulations are only to be ran on the server."); return; } float milisecondsDelay = NetworkTransport.GetCurrentRTT(NetworkingManager.singleton.hostId, clientId, out error) / 2f; Simulate(milisecondsDelay * 1000f, action); }
public int GetCurrentRTT(uint clientId, out byte error) { NetId netId = new NetId(clientId); if (netId.IsServer()) { netId.ConnectionId = (ushort)serverConnectionId; netId.HostId = (byte)serverHostId; } return(NetworkTransport.GetCurrentRTT(netId.HostId, netId.ConnectionId, out error)); }
public static float GetPing(int playerId) { foreach (KeyValuePair <int, int> pID in connectionToPlayer) { if (playerId == pID.Value) { byte err; return(NetworkTransport.GetCurrentRTT(hostId, pID.Key, out err)); } } return(-1); }
public override ulong GetCurrentRtt(ulong clientId) { GetUnetConnectionDetails(clientId, out byte hostId, out ushort connectionId); if (UseMLAPIRelay) { return(0); } else { return((ulong)NetworkTransport.GetCurrentRTT((int)hostId, (int)connectionId, out byte error)); } }
public void Start() { byte error; if (isServer) { NetworkTransport.GetCurrentRTT(NetworkServer.serverHostId, connectionToClient.connectionId, out error); if ((NetworkError)error != NetworkError.Ok) { isDone = true; } } }
public string[] OnCall(ICommandSender sender, string[] args) { List <string> pinglist = new List <string>(); byte b; foreach (Player player in plugin.Server.GetPlayers()) { NetworkConnection conn = (player.GetGameObject() as GameObject).GetComponent <NicknameSync>().connectionToClient; pinglist.Add($"Name: {player.Name} IP: {player.IpAddress} Ping: {NetworkTransport.GetCurrentRTT(conn.hostId, conn.connectionId, out b)}ms"); } return(pinglist.ToArray()); }
private void Shoot() { byte error; var shouldRewind = !(hasAuthority && isServer); if (shouldRewind) { Debug.Log("Should rewind!"); var rtt = NetworkTransport.GetCurrentRTT( connectionToClient.hostId, connectionToClient.connectionId, out error); var allRewindablePlayers = GameObject.FindObjectsOfType <MJPlayerController>(); for (var i = 0; i < allRewindablePlayers.Length; i++) { if (allRewindablePlayers[i] == this) { continue; } Debug.Log("Rewinding player for connection " + allRewindablePlayers[i].connectionToClient.connectionId); allRewindablePlayers[i].Rewind(rtt / 1000f); } } RaycastHit hit; if (Physics.Raycast(muzzle.position, muzzle.forward, out hit, shootDistance)) { RpcShowShot(muzzle.position, hit.point, true); } else { RpcShowShot(muzzle.position, muzzle.position + muzzle.forward * shootDistance, false); } if (shouldRewind) { var allRewindablePlayers = GameObject.FindObjectsOfType <MJPlayerController>(); for (var i = 0; i < allRewindablePlayers.Length; i++) { if (allRewindablePlayers[i] == this) { continue; } Debug.Log("Resetting player for connection " + allRewindablePlayers[i].connectionToClient.connectionId); allRewindablePlayers[i].Reset(); } } }
public int?GetRoundTripTimeToClientInMilliseconds(int clientConnectionId) { if (!socketId.HasValue) { return(null); } byte networkErrorAsByte; var rttInMs = NetworkTransport.GetCurrentRTT(socketId.Value, clientConnectionId, out networkErrorAsByte); var networkError = (NetworkError)networkErrorAsByte; return((networkError == NetworkError.Ok) ? rttInMs : (int?)null); }
public int GetRTT() { byte error; int rtt = NetworkTransport.GetCurrentRTT(hostId, connectionId, out error); NetworkError nerror = (NetworkError)error; if (nerror != NetworkError.Ok) { UnityEngine.Debug.LogError("Network error: " + nerror); } return(rtt); }
public override ConnectionStats GetConnectionStats(int connectionId) { var stats = new ConnectionStats(); byte error; stats.TotalBytesOut = NetworkTransport.GetOutgoingFullBytesCountForConnection(HostID, connectionId, out error); UNETUtility.HandleError(error); stats.CurrentRTT = NetworkTransport.GetCurrentRTT(HostID, connectionId, out error); UNETUtility.HandleError(error); stats.IncomingPacketsCount = NetworkTransport.GetIncomingPacketCount(HostID, connectionId, out error); UNETUtility.HandleError(error); stats.IncomingPacketsLost = NetworkTransport.GetIncomingPacketLossCount(HostID, connectionId, out error); UNETUtility.HandleError(error); return(stats); }
public FrameElements Rewind(NetworkConnection conn, bool includeClientBuffer = true, bool includeClientInterpolation = true) { byte error = 0; // return half the current RTT for this connect. Hostid of -1 should mean that this is the host, so there should be no latency. float RTT = (conn == null || conn.hostId == -1) ? 0 : .001f * NetworkTransport.GetCurrentRTT(conn.hostId, conn.connectionId, out error); // TODO: these may already be factored in, think about this. float clientOffset = ((includeClientBuffer && nst.hasAuthority) ? NSTSettings.single.desiredBufferMS : 0) + ((includeClientInterpolation && nst.hasAuthority) ? NetworkSyncTransform.frameUpdateInterval : 0); return(Rewind(RTT + clientOffset)); }
public NetworkStats GetNetworkStats(int?connectionId) { byte errorAsByte; var networkStats = new NetworkStats { RecentOutgoingBandwidthInBytes = bandwidthAverager.OutgoingBandwidthInBytes, IncomingPacketCountForAllHosts = NetworkTransport.GetIncomingPacketCountForAllHosts(), IncomingPacketDropCountForAllHosts = NetworkTransport.GetIncomingPacketDropCountForAllHosts(), NetworkTimestamp = NetworkTransport.GetNetworkTimestamp(), OutgoingFullBytesCount = NetworkTransport.GetOutgoingFullBytesCount(), OutgoingMessageCount = NetworkTransport.GetOutgoingMessageCount(), OutgoingPacketCount = NetworkTransport.GetOutgoingPacketCount(), OutgoingSystemBytesCount = NetworkTransport.GetOutgoingSystemBytesCount(), OutgoingUserBytesCount = NetworkTransport.GetOutgoingUserBytesCount(), }; if (socketId.HasValue) { networkStats.IncomingMessageQueueSize = NetworkTransport.GetIncomingMessageQueueSize(socketId.Value, out errorAsByte); networkStats.OutgoingFullBytesCountForHost = NetworkTransport.GetOutgoingFullBytesCountForHost(socketId.Value, out errorAsByte); networkStats.OutgoingMessageCountForHost = NetworkTransport.GetOutgoingMessageCountForHost(socketId.Value, out errorAsByte); networkStats.OutgoingMessageQueueSize = NetworkTransport.GetOutgoingMessageQueueSize(socketId.Value, out errorAsByte); networkStats.OutgoingPacketCountForHost = NetworkTransport.GetOutgoingPacketCountForHost(socketId.Value, out errorAsByte); networkStats.OutgoingSystemBytesCountForHost = NetworkTransport.GetOutgoingSystemBytesCountForHost(socketId.Value, out errorAsByte); networkStats.OutgoingUserBytesCountForHost = NetworkTransport.GetOutgoingUserBytesCountForHost(socketId.Value, out errorAsByte); if (connectionId.HasValue) { networkStats.AckBufferCount = NetworkTransport.GetAckBufferCount(socketId.Value, connectionId.Value, out errorAsByte); networkStats.CurrentRTT = NetworkTransport.GetCurrentRTT(socketId.Value, connectionId.Value, out errorAsByte); networkStats.IncomingPacketCount = NetworkTransport.GetIncomingPacketCount(socketId.Value, connectionId.Value, out errorAsByte); networkStats.IncomingPacketLossCount = NetworkTransport.GetIncomingPacketLossCount(socketId.Value, connectionId.Value, out errorAsByte); networkStats.MaxAllowedBandwidth = NetworkTransport.GetMaxAllowedBandwidth(socketId.Value, connectionId.Value, out errorAsByte); networkStats.OutgoingFullBytesCountForConnection = NetworkTransport.GetOutgoingFullBytesCountForConnection(socketId.Value, connectionId.Value, out errorAsByte); networkStats.OutgoingMessageCountForConnection = NetworkTransport.GetOutgoingMessageCountForConnection(socketId.Value, connectionId.Value, out errorAsByte); networkStats.OutgoingPacketCountForConnection = NetworkTransport.GetOutgoingPacketCountForConnection(socketId.Value, connectionId.Value, out errorAsByte); networkStats.OutgoingPacketNetworkLossPercent = NetworkTransport.GetOutgoingPacketNetworkLossPercent(socketId.Value, connectionId.Value, out errorAsByte); networkStats.OutgoingPacketOverflowLossPercent = NetworkTransport.GetOutgoingPacketOverflowLossPercent(socketId.Value, connectionId.Value, out errorAsByte); networkStats.OutgoingSystemBytesCountForConnection = NetworkTransport.GetOutgoingSystemBytesCountForConnection(socketId.Value, connectionId.Value, out errorAsByte); networkStats.OutgoingUserBytesCountForConnection = NetworkTransport.GetOutgoingUserBytesCountForConnection(socketId.Value, connectionId.Value, out errorAsByte); } } return(networkStats); }
/// <summary> /// Get the RTT to the server. /// </summary> /// <returns></returns> public int Ping() { if (!IsConnected) { return(0); } if (IsServer) { return(0); } int rtt = NetworkTransport.GetCurrentRTT(m_HostID, ConnectionID, out byte err); if ((NetworkError)err != NetworkError.Ok) { DebugLogError("Get RTT Error: " + (NetworkError)err); return(0); } return(rtt); }
private void Update() { byte error; //_slowConnectTimer += Time.deltaTime; if (MS_connectionID != -1) { _currentRTT = NetworkTransport.GetCurrentRTT(MS_socketID, MS_connectionID, out error); if (Time.time - _currentRate > _updateRate) { Debug.Log(_currentRTT); _currentRate = Time.time; } } int incomingSocketID = 0; int incomingConnectionID = 0; int incomingChannelID = 0; // POSSIBLY MOVE THIS TO BE A PERMANENT VARIABLE TO SAVE ALLOCATION RESOURCES byte[] incomingMessageBuffer = new byte[_bufferSize]; int dataSize = 0; NetworkEventType incomingNetworkEvent = NetworkTransport.Receive(out incomingSocketID, out incomingConnectionID, out incomingChannelID, incomingMessageBuffer, _bufferSize, out dataSize, out error); switch (incomingNetworkEvent) { case NetworkEventType.Nothing: break; case NetworkEventType.ConnectEvent: Debug.Log("Socket: " + incomingSocketID); Debug.Log("Connection: " + incomingConnectionID); Debug.Log("client incoming connection event received"); Debug.Log(incomingSocketID); // If connected to the master server, register as a client if (incomingSocketID == 0) { if (!_connected) { _connected = true; _statusWindow.UpdateOnlineStatus(true); } string jsonToBeSent = "3"; jsonToBeSent += JsonUtility.ToJson(""); SendJSONMessageToMaster(jsonToBeSent, QosType.Reliable); } // Send all the user information to the Game server so it can be used in game. else if (incomingSocketID == 1) { string jsonToBeSent = "3"; LoginInfo info = new LoginInfo(); info.username = _username; jsonToBeSent += JsonUtility.ToJson(info); SendJSONMessageToGame(jsonToBeSent, QosType.Reliable); } break; //0 for username/password info, 1 for PlayerIO case NetworkEventType.DataEvent: string message = Encoding.UTF8.GetString(incomingMessageBuffer); int prefix = 0; int index; string newMessage = ""; // New parser now allows client commands to be > 1 digit for (index = 0; index < message.Length; ++index) { if (message[index] == '{') { break; } } prefix = Convert.ToInt32(message.Substring(0, index)); newMessage = message.Substring(index); if (prefix == (int)ClientCommands.StartStream) { _currentFrame = -1; WindowManager.Instance.ToggleWindows(WindowIDs.GameSelect, WindowIDs.ClientLobby); _gameCanvas.gameObject.SetActive(true); } else if (prefix == (int)ClientCommands.RenderGame) { Texture2D gameTexture = new Texture2D(0, 0); ServerObject JSONdata = JsonUtility.FromJson <ServerObject>(newMessage); // Latency Mitigation at its finest. if (JSONdata.frameNum > _currentFrame) { byte[] textureByteArray = Convert.FromBase64String(JSONdata.texture); gameTexture.LoadImage(textureByteArray); _currentFrame = JSONdata.frameNum; _renderTo.GetComponent <CanvasRenderer>().SetTexture(gameTexture); } } else if (prefix == (int)ClientCommands.GoToGameSelect) { WindowManager.Instance.ToggleWindows(WindowIDs.Login, WindowIDs.GameSelect); } else if (prefix == (int)ClientCommands.AccountCreated) { WindowManager.Instance.ToggleWindows(WindowIDs.NewAccount, WindowIDs.NewAccountSuccess); } else if (prefix == (int)ClientCommands.PreExistingUser) { GameObject.Find("PasswordError").GetComponent <Text>().text = ""; GameObject.Find("UsernameError").GetComponent <Text>().text = "Username already exists. Choose a different username."; } else if (prefix == (int)ClientCommands.InvalidLogin) { GameObject.Find("LoginUsernameError").GetComponent <Text>().text = "Invalid username or password."; } else if (prefix == (int)ClientCommands.DoesNotExist) { GameObject.Find("LoginUsernameError").GetComponent <Text>().text = "Username does not exist in the database."; } else if (prefix == (int)ClientCommands.ActiveUser) { GameObject.Find("LoginUsernameError").GetComponent <Text>().text = "Username is already logged in."; } else if (prefix == (int)ClientCommands.CloseDisconnects) { _clientLobby.CannotDisconnect(); } else if (prefix == (int)ClientCommands.GoBackToMain) { _gameCanvas.gameObject.SetActive(false); WindowManager.Instance.ToggleWindows(WindowIDs.None, WindowIDs.GameSelect); byte e = 0; NetworkTransport.Disconnect(GS_socketID, GS_connectionID, out e); } else if (prefix == (int)ClientCommands.Occupancy) { //Do nothing... should connect } else if (prefix == (int)ClientCommands.NoOccupancy) { WindowManager.Instance.ToggleWindows(WindowIDs.GameSelect, WindowIDs.FullLobby); } else if (prefix == (int)ClientCommands.ForwardToGame) { GS_socketPort = JsonUtility.FromJson <PortID>(newMessage).portID; Debug.Log("GS_socketPort: " + GS_socketPort); ConnectToGame(); } else if (prefix == (int)ClientCommands.EnableControls) { _clientIO.gameInSession = true; WindowManager.Instance.ToggleWindows(WindowManager.Instance.currentWindow, WindowIDs.None); } else if (prefix == (int)ClientCommands.MaxInstances) { // reset other error messages GameObject.Find("PleaseWait").GetComponent <Text>().text = ""; // display error GameObject.Find("MaxNumInstance").GetComponent <Text>().text = "Maximum number of instances created."; } else if (prefix == (int)ClientCommands.GameBeingCreated) { // reset other error messages GameObject.Find("MaxNumInstance").GetComponent <Text>().text = ""; GameObject.Find("AvailableInstance").GetComponent <Text>().text = ""; GameObject.Find("PleaseWait").GetComponent <Text>().text = "Game is being loaded. Please wait a moment..."; } break; case NetworkEventType.DisconnectEvent: if (incomingSocketID == 0) { Debug.Log("client: disconnected from Master Server"); _connected = false; _gameCanvas.gameObject.SetActive(false); WindowManager.Instance.ToggleWindows(WindowManager.Instance.currentWindow, WindowIDs.StartWindow); WindowManager.Instance.ToggleWindows(WindowIDs.None, WindowIDs.OnlineStatus); _clientIO.gameInSession = false; MS_connectionID = -1; NetworkTransport.RemoveHost(MS_socketID); MS_socketID = -1; MS_connectionID = -1; _statusWindow.UpdateOnlineStatus(false); } else if (incomingSocketID == 1) { Debug.Log("client: disconnect from game server"); WindowManager.Instance.ToggleWindows(WindowManager.Instance.currentWindow, WindowIDs.GameSelect); NetworkTransport.RemoveHost(GS_socketID); _clientIO.gameInSession = false; GS_socketID = -1; GS_connectionID = -1; } break; } if ((WindowManager.Instance.currentWindow == WindowIDs.None || WindowManager.Instance.currentWindow == WindowIDs.ClientLobby) && _currentRTT >= _RTT_Threshold) { _disconnectTimer += Time.deltaTime; if (_disconnectTimer >= _timeThreshold) { //Network.Disconnect(); Debug.Log("disconnect from slow conection"); _gameCanvas.gameObject.SetActive(false); _clientIO.gameInSession = false; if (WindowManager.Instance.currentWindow == WindowIDs.ClientLobby) { WindowManager.Instance.ToggleWindows(WindowIDs.ClientLobby, WindowIDs.DisconnectWindow); } else if (WindowManager.Instance.currentWindow == WindowIDs.None) { WindowManager.Instance.ToggleWindows(WindowIDs.None, WindowIDs.DisconnectWindow); WindowManager.Instance.ToggleWindows(WindowIDs.None, WindowIDs.OnlineStatus); } LeaveLobby(); } } else { _disconnectTimer = 0.0f; } }
public float ClientGetRTT() { return(NetworkTransport.GetCurrentRTT(clientId, clientConnectionId, out error)); }
void Update() { int recHostId; int connectionId; int channelId; byte[] recBuffer = new byte[1024]; int bufferSize = 1024; int dataSize; byte error; rtt = NetworkTransport.GetCurrentRTT(hostID, connectionID, out error); if (rtt > 2500) { SendMessage(hostID, connectionID, myUnreliableChannelID, "Disconnect"); NetworkTransport.Disconnect(hostID, connectionID, out error); } NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error); switch (recData) { case NetworkEventType.Nothing: //1 break; case NetworkEventType.ConnectEvent: //2 Debug.Log("Connecting"); break; case NetworkEventType.DataEvent: //3 Stream stream = new MemoryStream(recBuffer); BinaryFormatter formatter = new BinaryFormatter(); string message = formatter.Deserialize(stream) as string; Debug.Log("incoming message event received: " + message); // Debug.Log ("RTT: " + rtt + "ms" ); // if (message.Contains ("rtt")) { // SendMessage (hostID, connectionID, myReliableChannelID, "rtt:" + rtt.ToString ()); // } if (message.Contains("players")) { string[] numberofplayers = message.Split(':'); numberOfPlayers = Int32.Parse(numberofplayers [1]); } if (message.Contains("timer")) { string[] time = message.Split(':'); float timer = float.Parse(time[1]); GameObject.FindGameObjectWithTag("MainCamera").GetComponent <countdownTimer> ().timeRemaining = timer; } if (message.Contains("addfrog")) { froglist.Add(Instantiate(frog, new Vector3(-5.0f, -4.5f, 0f), Quaternion.identity)); } if (message.Contains("number:")) { if (!playerassigned) { playerNumber = Int32.Parse(message.Replace("number: ", "")); numberOfPlayers += playerNumber; playerassigned = true; } else { numberOfPlayers++; } } // if (message.Contains ("Seed: ")) { // seed = Int32.Parse(message.Replace("Seed: ", "")); // } if (message.Contains("change")) { SceneManager.LoadScene("GameScene"); // froglist = GetComponent<GameManager> ().froglist; InstantiateFrogs(); for (int i = 0; i < numberOfPlayers; i++) { froglist [i].GetComponent <Frog> ().playerNumber = i; if (froglist [i].GetComponent <Frog> ().playerNumber == playerNumber) { froglist [i].GetComponent <Frog> ().localplayer = true; } } GUIenabled = false; } // if (message.Contains ("single")) { // string[] position = message.Replace("single:", "").Split (','); // float x = float.Parse(position[0]); // float y = float.Parse(position[1]); // froglist[playerNumber].transform.position = new Vector2(x, y); // } if (message.Contains("gone")) { string[] todelete = message.Split(':'); int playertodelete = Int32.Parse(todelete [1]); Destroy(froglist [playertodelete]); froglist [playertodelete] = null; numberOfPlayers--; } if (message.Contains("loc")) { string[] locations = message.Split('\n'); foreach (string location in locations) { if (location != "") { string[] playerlocations = location.Split(':'); int playerNumber = Int32.Parse(playerlocations [1]); string[] position = playerlocations [2].Split(','); float x = float.Parse(position [0]); float y = float.Parse(position [1]); string[] rotation = playerlocations [3].Split(','); float z = float.Parse(rotation [2]); froglist [playerNumber].GetComponent <Frog> ().newRotation.eulerAngles = new Vector3(0, 0, z); froglist [playerNumber].transform.position = new Vector2(x, y); } } } if (message.Contains("scores")) { string[] scores = message.Split('\n'); foreach (string score in scores) { if (score != "") { string[] playerscores = score.Split(':'); int playerNumber = Int32.Parse(playerscores [1]); int numberscore = Int32.Parse(playerscores [2]); froglist [playerNumber].GetComponent <Frog> ().points = numberscore; } } } if (message.Contains("Spawn")) { string[] spawners = message.Split(':'); string area = spawners [1]; string[] spawnloc = spawners [2].Split(','); float x = float.Parse(spawnloc [0]); float y = float.Parse(spawnloc [1]); if (area == "3") { GameObject[] spawnlist = GameObject.FindGameObjectsWithTag("Area3"); foreach (GameObject spawn in spawnlist) { if (spawn.transform.position.x == x && spawn.transform.position.y == y) { spawn.GetComponent <PlaneSpawner> ().spawn = true; } } } else { GameObject[] spawnlist = GameObject.FindGameObjectsWithTag("Area" + area); foreach (GameObject spawn in spawnlist) { if (spawn.transform.position.x == x && spawn.transform.position.y == y) { if (spawn.GetComponent <CarSpawner> () != null) { spawn.GetComponent <CarSpawner> ().spawn = true; } if (spawn.GetComponent <WoodSpawner> () != null) { spawn.GetComponent <WoodSpawner> ().spawn = true; } // if (spawn.GetComponent<PlaneSpawner>() != null) // spawn.GetComponent<PlaneSpawner> ().spawn = true; } } } } if (message.Contains("Tongue")) { string[] tongue = message.Split(':'); int persontonguing = Int32.Parse(tongue [1]); froglist [persontonguing].GetComponent <Frog> ().ShootTongue(); } break; case NetworkEventType.DisconnectEvent: //4 Debug.Log("Disconnected, Game Over"); break; } if (Input.GetKeyDown(KeyCode.UpArrow)) { SendMessage(hostID, connectionID, myReliableChannelID, "UP"); } if (Input.GetKeyDown(KeyCode.DownArrow)) { SendMessage(hostID, connectionID, myReliableChannelID, "DOWN"); } if (Input.GetKeyDown(KeyCode.RightArrow)) { SendMessage(hostID, connectionID, myReliableChannelID, "RIGHT"); } if (Input.GetKeyDown(KeyCode.LeftArrow)) { SendMessage(hostID, connectionID, myReliableChannelID, "LEFT"); } if (Input.GetKeyDown(KeyCode.Space)) { SendMessage(hostID, connectionID, myReliableChannelID, "SPACE"); } }
public int GetCurrentRTT(int hostId, int connectionId, out byte error) { return(NetworkTransport.GetCurrentRTT(hostId, connectionId, out error)); }
/// <summary> /// Get the ping for a specified networkconnection (Round trip) /// </summary> /// <param name="client">Client you want to get the ping for</param> /// <returns>Round trip ping in milliseconds</returns> public static int GetPing(NetworkConnection client) { byte err; return(NetworkTransport.GetCurrentRTT(Instance._HostId, client.ConnectionId, out err)); }
void Update() { int recHostId; int connectionId; int channelId; byte[] recBuffer = new byte[1024]; int bufferSize = 1024; int dataSize; byte error; if (hostReady && Ready) { Ready = false; //gameStarted = true; SceneManager.LoadScene("Game"); } if (dead) { dead = false; Debug.Log("Dying"); Dying = true; Util.SendSocketMessage(hostSocketID, hostConnectionID, tcpID, "dead: " + playerNum); //StartCoroutine(checkIfCamMove()); } NetworkEventType recData = NetworkEventType.DataEvent; while (recData != NetworkEventType.Nothing) { recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error); switch (recData) { case NetworkEventType.Nothing: break; case NetworkEventType.ConnectEvent: Debug.Log("incoming connection event received"); OnJoinGame(); break; case NetworkEventType.DataEvent: Stream stream = new MemoryStream(recBuffer); BinaryFormatter formatter = new BinaryFormatter(); string message = formatter.Deserialize(stream) as string; //Debug.Log(message); if (message.Contains("pnum: ")) { Debug.Log("incoming message event received: " + message); playerNum = Int32.Parse(message.Replace("pnum: ", "")); } else if (message.Contains("seed: ")) { LevelGenerator.Seed = Int32.Parse(message.Replace("seed: ", "")); } else if (message.Contains("Ready")) { hostReady = true; } else if (message.Contains("pl")) { ParseGameState(message); } else if (message.Contains("anim: ")) { string pa = message.Replace("anim: ", ""); playerAnims = pa.Split(',').Select(int.Parse).ToList(); } else if (message.Contains("numi")) { numPlayersInGame = int.Parse(message.Replace("numi: ", "")); } else if (message.Contains("nump: ")) { numPlayers = int.Parse(message.Replace("nump: ", "")); Util.SendSocketMessage(hostSocketID, hostConnectionID, tcpID, "name: " + username); } else if (message.Contains("pnames: ")) { Debug.Log(message); string[] playerNames = message.Replace("pnames: ", "").Split(','); foreach (string pName in playerNames) { if (pName.Length > 0) // No phantom players { LobbyManager.Instance.GetServerByName(playerNames[0].ToLower()).AddPlayer(new PlayerInfo(pName, "Joined")); } } } else if (message.Contains("dead: ")) { int deadPlayerNum = Int32.Parse(message.Replace("dead: ", "")); if (deadPlayerNum != playerNum) { players[deadPlayerNum].SetActive(false); //Play animation for other player //Tell everyone they died(Broadcast death) } } else if (message.Contains("start: ")) { gameStarted = true; StartCoroutine(checkIfCamMove()); } else if (message.Contains("reset: ")) { dead = false; LevelGenerator.Seed = int.Parse(message.Replace("reset: ", "")); Debug.Log("reset dying"); Dying = false; currPlayerScript.gameOver = true; EndGameBool = true; } else if (message.Contains("endgame: ")) { string winningPlayer = message.Replace("endgame: ", ""); GameObject winText = Instantiate(winnerTextPrefab, GameObject.Find("Canvas").transform); winText.GetComponent <Text>().text = "The winner is " + winningPlayer; } else if (message.Contains("dc: ")) { GameObject p = players[int.Parse(message.Replace("dc: ", ""))]; players.Remove(p); p.SetActive(false); } else if (message.Contains("spectate: ")) { string pa = message.Replace("spectate: ", ""); playerAnims = pa.Split(',').Select(int.Parse).ToList(); spectating = true; SceneManager.LoadScene("Game"); } if (message.Contains("msg:")) { string actualMsg = message.Replace("msg:", ""); Chatbox.Instance.ShowMessage(actualMsg); } if (message.Contains("sess_end")) { sessionEnd = true; } break; case NetworkEventType.DisconnectEvent: Debug.Log("remote client event disconnected"); break; } } if (gameStarted && !spectating) { if (lastHoriz != Input.GetAxis("Horizontal")) { lastHoriz = Input.GetAxis("Horizontal"); Util.SendSocketMessage(hostSocketID, hostConnectionID, udpID, "h: " + stopwatch.ElapsedMilliseconds + ":" + lastHoriz); //Added timestamp to input. } int ping = NetworkTransport.GetCurrentRTT(hostSocketID, hostConnectionID, out error); if (pingText) { pingText.text = "Ping: " + ping; } StartCoroutine(DelayInput(Input.GetAxis("Horizontal"), ping / 2 / 1000f)); } }
public int GetCurrentRTT(uint clientId, out byte error) { NetId netId = new NetId(clientId); return(NetworkTransport.GetCurrentRTT(netId.HostId, netId.ConnectionId, out error)); }