示例#1
0
        public async Task <PlayerUpdateResponse> UpdatePlayerLocation(double latitude, double longitude, double altitude)
        {
            //SetCoordinates(latitude, longitude, altitude);

            // This needs to me removed from here
            Client.CurrentLatitude  = latitude;
            Client.CurrentLongitude = longitude;
            Client.CurrentAltitude  = altitude;
            string latlngalt = latitude.ToString(CultureInfo.InvariantCulture) + ":" + longitude.ToString(CultureInfo.InvariantCulture) + ":" + altitude.ToString(CultureInfo.InvariantCulture);

            File.WriteAllText(Directory.GetCurrentDirectory() + "\\Configs\\LastCoords.txt", latlngalt);
            //

            var message = new PlayerUpdateMessage
            {
                Latitude  = Client.CurrentLatitude,
                Longitude = Client.CurrentLongitude
            };

            Logger.Debug($"Calling Request UpdatePlayerLocation -> {latitude} / {longitude} / {altitude}");
            var updatePlayerLocationRequestEnvelope = await GetRequestBuilder().GetRequestEnvelope(new Request[] {
                new Request
                {
                    RequestType    = RequestType.PlayerUpdate,
                    RequestMessage = message.ToByteString()
                }
            }).ConfigureAwait(false);

            return(await PostProtoPayload <Request, PlayerUpdateResponse>(updatePlayerLocationRequestEnvelope).ConfigureAwait(false));
        }
示例#2
0
 //NOTE: CURRENTLY NO TESTING FOR ANY SECURITY, ONE PLAYER COULD SEND FAKE PACKETS IF THEY WERE SMART ENOUGH AND RIG THE GAME
 public override void Update()
 {
     if (m_Server != null && m_Status != null)
     {
         m_Server.DispatchCallback(m_Status); //check for new or changed connections
         foreach (var c in m_Connections)
         {
             netMessageCount = m_Server.ReceiveMessagesOnConnection(c.Key, netMessages, maxMessages);
             m_NetworkMessageConnectionSource = c.Key;
             readNetworkMessages();
         }
         HandleNewConnection(); //simple add to m_Connections if necessary
         if (GameManager.Instance.HasGameStarted)
         {
             ClientPlayer cPlayer = GameManager.Instance.ClientPlayer;
             if (cPlayer != null)
             {
                 PlayerUpdateMessage cPlayerUpdateMsg = new PlayerUpdateMessage(FindObjectOfType <ClientPlayer>().m_PlayerInfo, GameManager.Instance.m_PlayerUsername);
                 SendMessageToAllPlayers(cPlayerUpdateMsg);
             }
         }
         if (GameManager.Instance.HasGameStarted && !GameManager.Instance.HasGameEnded)
         {
             CheckForBoundsLoss(); //check if any player fallen behind
         }
     }
 }
示例#3
0
    override public void parseMessage(string message)
    {
        Debug.Log(whoAmI() + "parsing message");
        NetworkMessage networkMessage = NetworkMessage.decodeMessage(message);
        string         messageType    = networkMessage.thisMessageType();

        if (messageType == typeof(PlayerUpdateMessage).FullName)
        {
            PlayerUpdateMessage joinMsg = (PlayerUpdateMessage)networkMessage;
            if (joinMsg.action == "join")
            {
                this.connectedPlayers.Add(new NetworkNode(joinMsg.ipAddress, Config.clientListenPort));
            }

            Debug.Log("[SERVER] client " + joinMsg.ipAddress + " " + joinMsg.action + "-ed ");

            // update everyone on who is online
            broadcastMessage(new JoinBroadcastMessage(connectedPlayerIps()));
        }
        else if (messageType == typeof(PingMessage).FullName)
        {
            Debug.Log("[SERVER] ping!");
        }
        else
        {
            broadcastMessage(networkMessage);
        }
    }
示例#4
0
        public async Task <PlayerUpdateResponse> UpdatePlayerLocation(double latitude, double longitude, double altitude)
        {
            SetCoordinates(latitude, longitude, altitude);
            var message = new PlayerUpdateMessage
            {
                Latitude  = _client.CurrentLatitude,
                Longitude = _client.CurrentLongitude
            };

            var updatePlayerLocationRequestEnvelope = RequestBuilder.GetRequestEnvelope(
                new Request
            {
                RequestType    = RequestType.PlayerUpdate,
                RequestMessage = message.ToByteString()
            });

            var updateResponse =
                await PostProtoPayload <Request, PlayerUpdateResponse>(updatePlayerLocationRequestEnvelope);

            lock (Client._lock)
            {
                _client._map.Invoke(new MethodInvoker(delegate {
                    var userOverlay = _client._map.Overlays[4];
                    userOverlay.Markers[0].Position = new GMap.NET.PointLatLng(_client.CurrentLatitude, _client.CurrentLongitude);
                }));
            }

            return(updateResponse);
        }
示例#5
0
            internal void SendClientInputPredictionsToServer(SimulationTickNumber currentSimTickNumber, NetworkMessageWriter networkMessageWriter)
            {
                for (int playerIdx = 0; playerIdx < _localPlayers.Count; playerIdx++)
                {
                    ref var player             = ref _localPlayers.Items[playerIdx];
                    var     inputSnapshotsComp = player.InputSnapshotsComponent;

                    PlayerUpdateMessage playerUpdateMsg = default;

                    var pendingInputs = inputSnapshotsComp.PendingInputs;
                    // Need to limit the number of input, eg. if there's a large delay in server ack response,
                    // then most likely it has lost some of our older input. Probably should be a config setting?
                    const int MaxPendingPlayerInputs = GameConfig.PhysicsSimulationRate * 20; // 20s worth of input
                    const int MaxSendPlayerInputs    = 10;                                    // We will only send 10 inputs max in a single packet, and accept the fact that older inputs may be lost
                    if (pendingInputs.Count >= MaxPendingPlayerInputs)
                    {
                        pendingInputs.RemoveRange(0, pendingInputs.Count - MaxPendingPlayerInputs + 1);
                    }
                    // Append the latest input
                    var findSnapshotResult = inputSnapshotsComp.SnapshotStore.TryFindSnapshot(currentSimTickNumber);
                    Debug.Assert(findSnapshotResult.IsFound);
                    pendingInputs.Add(findSnapshotResult.Result);

                    int sendInputCount = Math.Min(pendingInputs.Count, MaxSendPlayerInputs);
                    // At most, only send the last 10 inputs (ie. the current inputs) to not blow out the packet size.
                    int inputIndexOffset = pendingInputs.Count - sendInputCount;
                    for (int i = 0; i < sendInputCount; i++)
                    {
                        int inputIndex = i + inputIndexOffset;
                        if (pendingInputs[inputIndex].PlayerInputSequenceNumber > inputSnapshotsComp.ServerLastAcknowledgedPlayerInputSequenceNumber)
                        {
                            inputIndexOffset += i;
                            sendInputCount   -= i;
                            break;
                        }
                    }

                    networkMessageWriter.Reset();
                    playerUpdateMsg.AcknowledgedServerSimulationTickNumber = player.NetworkEntityComponent.LastAcknowledgedServerSimulationTickNumber;
                    playerUpdateMsg.WriteTo(networkMessageWriter);
                    PlayerUpdateInputMessage playerUpdateInputsMsg = default;
                    playerUpdateInputsMsg.WriteHeader(networkMessageWriter, (ushort)sendInputCount);

                    for (int i = 0; i < sendInputCount; i++)
                    {
                        int     inputIndex   = i + inputIndexOffset;
                        ref var curInputData = ref pendingInputs.Items[inputIndex];
                        playerUpdateInputsMsg.PlayerInputSequenceNumber = curInputData.PlayerInputSequenceNumber;
                        playerUpdateInputsMsg.MoveInput          = curInputData.MoveInput;
                        playerUpdateInputsMsg.JumpRequestedInput = curInputData.IsJumpButtonDown;

                        playerUpdateInputsMsg.WriteNextArrayItem(networkMessageWriter);
#if DEBUG
                        //if (curInputData.MoveInput.LengthSquared() > 0)
                        //{
                        //    _networkEntityProcessor.DebugWriteLine($"Cln SendInput Move: {curInputData.MoveInput} - PISeqNo: {curInputData.PlayerInputSequenceNumber}");
                        //}
#endif
                    }
示例#6
0
    private void ClientReceiveUpdate(NetworkMessage message)     //lo que recibe al conectarse
    {
        PlayerUpdateMessage msg = message.ReadMessage <PlayerUpdateMessage>();

        player.transform.position = msg.position;
        mov.speed = msg.speed;
        mov.lives = msg.lives;
    }
示例#7
0
    public static Message decipherMessage(byte[] msgBytes)
    {
        if (BitConverter.IsLittleEndian)
        {
            //Array.Reverse(msgBytes);
        }
        Message msg;

        byte[] eventTypeBytes = new byte[2];
        Buffer.BlockCopy(msgBytes, 0, eventTypeBytes, 0, 2);

        ushort       sho       = BitConverter.ToUInt16(eventTypeBytes, 0);
        NetworkEvent eventType = (NetworkEvent)sho;

        switch (eventType)
        {
        case NetworkEvent.StartGame:
            msg = new GameStartMessage(msgBytes);
            break;

        case NetworkEvent.PlayerUpdateInfo:
            msg = new PlayerUpdateMessage(msgBytes);
            break;

        case NetworkEvent.PlayerConnected:
            msg = new PlayerConnectedMessage(msgBytes);
            break;

        case NetworkEvent.PlayerDisconnected:
            msg = new PlayerDisconnectedMessage(msgBytes);
            break;

        case NetworkEvent.ObstacleGenerated:
            msg = new ObstacleGeneratedMessage(msgBytes);
            break;

        case NetworkEvent.PlayerFellBehind:
            msg = new PlayerFellBehindMessage(msgBytes);
            break;

        case NetworkEvent.ObstacleModified:
            msg = new ObstacleModifiedMessage(msgBytes);
            break;

        case NetworkEvent.PlayerWonRace:
            msg = new PlayerWonMessage(msgBytes);
            break;

        case NetworkEvent.PlayerAttackPlayer:
            msg = new PlayerAttackedPlayerMessage(msgBytes);
            break;

        default:
            throw new Exception("oops " + eventType);
        }
        return(msg);
    }
示例#8
0
    public override void HandleNetworkMessage(Message msg)
    {
        base.HandleNetworkMessage(msg);
        if (msg is PlayerConnectedMessage) //player sends this once connected to send name
        {
            PlayerConnectedMessage nMsg = msg as PlayerConnectedMessage;
            if (GameManager.Instance.GetPlayer(nMsg.playerID) != null) //player name already used, prepare to kick
            {
                m_ConnectionToAdd = new KeyValuePair <uint, string>(m_NetworkMessageConnectionSource, "");
            }
            else
            {
                m_ConnectionToAdd = new KeyValuePair <uint, string>(m_NetworkMessageConnectionSource, nMsg.playerID);
                //Send the player connected info to everyone
                ClientPlayer cP = GameManager.Instance.ClientPlayer;
                if (cP != null)
                {
                    SendMessageToAllExceptPlayer(nMsg.playerID, new PlayerConnectedMessage(nMsg.playerID), SendType.Reliable);
                }
                //send current players to the connected player
                List <Player> players = GameManager.Instance.m_Players;
                for (int i = 0; i < players.Count; i++)
                {
                    if (players[i] is ClientPlayer)
                    {
                        m_Server.SendMessageToConnection(m_NetworkMessageConnectionSource, new PlayerConnectedMessage(GameManager.Instance.m_PlayerUsername).toBuffer(), SendType.Reliable);
                    }
                    else
                    {
                        m_Server.SendMessageToConnection(m_NetworkMessageConnectionSource, new PlayerConnectedMessage((players[i] as NetworkedPlayer).playerID).toBuffer(), SendType.Reliable);
                    }
                }
                GameManager.Instance.AddPlayer(nMsg.playerID);
                Invoke("RealignPlayersAndSend", 0.1f); //need a delay for them to add the player
            }
        }
        if (msg is PlayerUpdateMessage)
        {
            PlayerUpdateMessage nMsg = msg as PlayerUpdateMessage;
            GameManager.Instance.UpdatePlayerInformation(ref nMsg.info, nMsg.playerID);
            SendMessageToAllExceptPlayer(nMsg.playerID, nMsg);
        }
        if (msg is ObstacleModifiedMessage)
        {
            Debug.Log("Obstacle Modified Message");
            ObstacleModifiedMessage nMsg = msg as ObstacleModifiedMessage;
            SendMessageToAllExceptPlayer(nMsg.playerID, nMsg, SendType.Reliable);
            (GameManager.Instance.m_AllObstacles[(int)nMsg.obstacleID] as IObstacle).InteractedWith(GameManager.Instance.GetPlayer(nMsg.playerID));
        }

        if (msg is PlayerAttackedPlayerMessage)
        {
            PlayerAttackedPlayerMessage nMsg = msg as PlayerAttackedPlayerMessage;
            SendMessageToAllExceptPlayer(nMsg.attackeePlayerID, nMsg, SendType.Reliable);
            GameManager.Instance.PlayerAttacked(nMsg.attackedPlayerID);
        }
    }
示例#9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <param name="accuracy"></param>
        /// <returns></returns>
        public bool QueueUpdatePlayerLocationRequest(double latitude, double longitude, double accuracy)
        {
            SetCoordinates(latitude, longitude, accuracy);
            var message = new PlayerUpdateMessage
            {
                Latitude  = Client.CurrentPosition.Latitude,
                Longitude = Client.CurrentPosition.Longitude,
            };

            return(Client.QueueRequest(RequestType.PlayerUpdate, message));
        }
示例#10
0
        public async Task <PlayerUpdateResponse> UpdatePlayerLocation(double lat, double lng, double alt)
        {
            SetCoordinates(lat, lng, alt);
            PlayerUpdateMessage playerUpdateMessage = new PlayerUpdateMessage()
            {
                Latitude  = CurrentLat,
                Longitude = CurrentLng
            };

            return(await AwaitableOnResponseFor <PlayerUpdateMessage, PlayerUpdateResponse>(playerUpdateMessage, RequestType.PlayerUpdate));
        }
示例#11
0
 public override void HandleNetworkMessage(Message msg)
 {
     base.HandleNetworkMessage(msg);
     if (msg is GameStartMessage)
     {
         GameStartMessage nMsg  = msg as GameStartMessage;
         ConnectionStatus cStat = new ConnectionStatus();
         m_Server.GetQuickConnectionStatus(m_Connection, cStat);
         uniformTimeOffset = ((nMsg.uniformTime.Ticks / TimeSpan.TicksPerSecond) + (((float)cStat.ping) * 0.01f)) - (DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond);
         GameManager.Instance.StartGameInSeconds(nMsg.timeAfterToSpawn + uniformTimeOffset);
     }
     if (msg is PlayerConnectedMessage)
     {
         PlayerConnectedMessage nMsg = msg as PlayerConnectedMessage;
         NetworkedPlayer        p    = GameManager.Instance.AddPlayer(nMsg.playerID);
         p.playerID = nMsg.playerID;
     }
     else if (msg is PlayerDisconnectedMessage)
     {
         PlayerDisconnectedMessage nMsg = msg as PlayerDisconnectedMessage;
         GameManager.Instance.RemovePlayer(nMsg.playerID);
     }
     else if (msg is PlayerUpdateMessage)
     {
         PlayerUpdateMessage nMsg = msg as PlayerUpdateMessage;
         GameManager.Instance.UpdatePlayerInformation(ref nMsg.info, nMsg.playerID);
     }
     else if (msg is ObstacleGeneratedMessage)
     {
         ObstacleGeneratedMessage nMsg = msg as ObstacleGeneratedMessage;
         TileManager.Instance.SpawnObstacle(nMsg.itemID, nMsg.itemPos, nMsg.itemType);
     }
     else if (msg is ObstacleModifiedMessage)
     {
         ObstacleModifiedMessage nMsg = msg as ObstacleModifiedMessage;
         (GameManager.Instance.m_AllObstacles[(int)nMsg.obstacleID] as IObstacle).InteractedWith(GameManager.Instance.GetPlayer(nMsg.playerID));
     }
     else if (msg is PlayerFellBehindMessage)
     {
         PlayerFellBehindMessage nMsg = msg as PlayerFellBehindMessage;
         GameManager.Instance.PlayerFellBehind(nMsg.playerID);
     }
     else if (msg is PlayerWonMessage)
     {
         PlayerWonMessage nMsg = msg as PlayerWonMessage;
         GameManager.Instance.PlayerHasWonGame(GameManager.Instance.GetPlayer(nMsg.playerID));
     }
     else if (msg is PlayerAttackedPlayerMessage)
     {
         PlayerAttackedPlayerMessage nMsg = msg as PlayerAttackedPlayerMessage;
         GameManager.Instance.PlayerAttacked(nMsg.attackedPlayerID);
     }
 }
示例#12
0
    private void ServerReceiveUpdate(NetworkMessage message)     //cuando se conecta algun jugador
    {
        //PlayerTypeMessage msg = message.ReadMessage<PlayerTypeMessage>();

        PlayerUpdateMessage msg = new PlayerUpdateMessage();

        msg.position = playerpos;
        msg.speed    = speed;
        msg.lives    = lives;

        //NetworkServer.SendToAll(MsgType.Connect, msg);
    }
示例#13
0
        public async Task <PlayerUpdateResponse> UpdatePlayerLocation(double latitude, double longitude, double altitude)
        {
            SetCoordinates(latitude, longitude, altitude);
            var message = new PlayerUpdateMessage
            {
                Latitude  = Client.CurrentLatitude,
                Longitude = Client.CurrentLongitude
            };

            var updatePlayerLocationRequestEnvelope = RequestBuilder.GetRequestEnvelope(
                new Request
            {
                RequestType    = RequestType.PlayerUpdate,
                RequestMessage = message.ToByteString()
            });

            return(await PostProtoPayload <Request, PlayerUpdateResponse>(updatePlayerLocationRequestEnvelope));
        }
示例#14
0
        public async Task<PlayerUpdateResponse> UpdatePlayerLocation(double latitude, double longitude, double altitude)
        {
            SetCoordinates(latitude, longitude, altitude);
            var message = new PlayerUpdateMessage
            {
                Latitude = _client.CurrentLatitude,
                Longitude = _client.CurrentLongitude
            };

            var updatePlayerLocationRequestEnvelope = RequestBuilder.GetRequestEnvelope(
                new Request
                {
                    RequestType = RequestType.PlayerUpdate,
                    RequestMessage = message.ToByteString()
                });

            return await PostProtoPayload<Request, PlayerUpdateResponse>(updatePlayerLocationRequestEnvelope);
        }
示例#15
0
        private Task OnPlayerUpdate(PlayerUpdateMessage message)
        {
            var plr = _playerManager[message.AccountId];

            if (plr == null)
            {
                _logger.Warning("<OnPlayerUpdate> Cant find player={Id}", message.AccountId);
                return(Task.CompletedTask);
            }

            plr.TotalExperience = message.TotalExperience;
            plr.RoomId          = message.RoomId;
            plr.TeamId          = message.TeamId;

            var channel = plr.Channel;

            channel.Broadcast(new SUserDataAckMessage(plr.Map <Player, UserDataDto>()));
            return(Task.CompletedTask);
        }
示例#16
0
    void parseConnectionSearchMessage(string message)
    {
        try {
            NetworkMessage networkMessage = NetworkMessage.decodeMessage(message);
            string         messageType    = networkMessage.thisMessageType();
            Debug.Log("[CLIENT] got connection ping from server. " + message);
            if (messageType == typeof(DiscoveryPingMessage).FullName)
            {
                DiscoveryPingMessage dpm = (DiscoveryPingMessage)networkMessage;
                this.node       = new NetworkNode(dpm.sourceIp.ToString(), Config.serverListenPort);
                this.serverNode = new NetworkNode(dpm.sourceIp.ToString(), Config.clientListenPort);
                startListening(this.serverNode);

                // send initial connection message
                ipAddress = NetworkService.GetSelfIP();
                PlayerUpdateMessage joinMsg = new PlayerUpdateMessage(ipAddress, "join");
                this.sendMessageToServer(joinMsg);
                serverDiscoveryClient.Close();
            }
        } catch (Exception e) {
            Debug.Log(whoAmI() + e);
        }
    }
示例#17
0
 private void HandlePlayerUpdate(PlayerUpdateMessage playerUpdate)
 {
     Player = playerUpdate.Player;
 }