Exemplo n.º 1
0
        // called after successful authentication
        void OnServerAuthenticated(INetworkPlayer player)
        {
            logger.Log("NetworkSceneManager.OnServerAuthenticated");

            player.Send(new SceneMessage {
                scenePath = ActiveScenePath, additiveScenes = additiveSceneList.ToArray()
            });
            player.Send(new SceneReadyMessage());
        }
Exemplo n.º 2
0
        /// <summary>
        ///     When player authenticates to server we send a message to them to load up main scene and
        ///     any other scenes that are loaded on server.
        ///
        ///     <para>Default implementation takes main activate scene as main and any other loaded scenes and sends it to player's
        ///     Please override this function if this is not intended behavior for you.</para>
        /// </summary>
        /// <param name="player">The current player that finished authenticating.</param>
        protected internal virtual void OnServerAuthenticated(INetworkPlayer player)
        {
            logger.Log("[NetworkSceneManager] - OnServerAuthenticated");

            var additiveScenes = GetAdditiveScenes();

            player.Send(new SceneMessage {
                MainActivateScene = ActiveScenePath, AdditiveScenes = additiveScenes
            });
            player.Send(new SceneReadyMessage());
        }
Exemplo n.º 3
0
        internal void SendSpawnMessage(NetworkIdentity identity, INetworkPlayer player)
        {
            // for easier debugging
            if (logger.LogEnabled())
            {
                logger.Log("Server SendSpawnMessage: name=" + identity.name + " sceneId=" + identity.sceneId.ToString("X") + " netid=" + identity.NetId);
            }

            // one writer for owner, one for observers
            using (PooledNetworkWriter ownerWriter = NetworkWriterPool.GetWriter(), observersWriter = NetworkWriterPool.GetWriter())
            {
                bool isOwner = identity.ConnectionToClient == player;

                ArraySegment <byte> payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter);

                player.Send(new SpawnMessage
                {
                    netId         = identity.NetId,
                    isLocalPlayer = player.Identity == identity,
                    isOwner       = isOwner,
                    sceneId       = identity.sceneId,
                    assetId       = identity.AssetId,
                    // use local values for VR support
                    position = identity.transform.localPosition,
                    rotation = identity.transform.localRotation,
                    scale    = identity.transform.localScale,

                    payload = payload,
                });
            }
        }
Exemplo n.º 4
0
 public void OnClientAuthenticated(INetworkPlayer player)
 {
     // tell the server to create a player with this name
     player.Send(new CreateCharacterMessage {
         name = PlayerName
     });
 }
Exemplo n.º 5
0
 public override void ClientAuthenticate(INetworkPlayer player)
 {
     // The serverCode should be set on the client before connection to the server.
     // When the client connects it sends the code and the server checks that it is correct
     player.Send(new AuthRequestMessage
     {
         serverCode = serverCode,
     });
 }
Exemplo n.º 6
0
        internal void SendRemoveAuthorityMessage(NetworkIdentity identity, INetworkPlayer previousOwner)
        {
            if (logger.LogEnabled())
            {
                logger.Log($"Server SendRemoveAuthorityMessage: name={identity.name} sceneId={identity.SceneId:X} netId={identity.NetId}");
            }

            previousOwner.Send(new RemoveAuthorityMessage
            {
                netId = identity.NetId,
            });
        }
Exemplo n.º 7
0
        public override void OnClientAuthenticate(INetworkPlayer player)
        {
            player.RegisterHandler <AuthResponseMessage>(OnAuthResponseMessage);

            var authRequestMessage = new AuthRequestMessage
            {
                AuthUsername = Username,
                AuthPassword = Password
            };

            player.Send(authRequestMessage);
        }
Exemplo n.º 8
0
        public static void SendTarget(NetworkBehaviour behaviour, int index, NetworkWriter writer, int channelId, INetworkPlayer player)
        {
            var message = CreateMessage(behaviour, index, writer);

            // connection parameter is optional. use owner if null
            if (player == null)
            {
                player = behaviour.Owner;
            }

            player.Send(message, channelId);
        }
Exemplo n.º 9
0
        // you can send the message here if you already know
        // everything about the character at the time of player
        // or at a later time when the user submits his preferences
        private void OnClientAuthenticated(INetworkPlayer player)
        {
            var mmoCharacter = new CreateMMOCharacterMessage
            {
                // populate the message with your data
                name      = "player name",
                race      = Race.Human,
                eyeColor  = Color.red,
                hairColor = Color.black,
            };

            player.Send(mmoCharacter);
        }
Exemplo n.º 10
0
        public void OnAuthRequestMessage(INetworkPlayer player, AuthRequestMessage msg)
        {
            if (logger.LogEnabled())
            {
                logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", msg.AuthUsername, msg.AuthPassword);
            }

            // check the credentials by calling your web server, database table, playfab api, or any method appropriate.
            if (msg.AuthUsername == Username && msg.AuthPassword == Password)
            {
                // create and send msg to client so it knows to proceed
                var authResponseMessage = new AuthResponseMessage
                {
                    Code    = 100,
                    Message = "Success"
                };

                player.Send(authResponseMessage);

                // Invoke the event to complete a successful authentication
                base.OnServerAuthenticate(player);
            }
            else
            {
                // create and send msg to client so it knows to disconnect
                var authResponseMessage = new AuthResponseMessage
                {
                    Code    = 200,
                    Message = "Invalid Credentials"
                };

                player.Send(authResponseMessage);

                // disconnect the client after 1 second so that response message gets delivered
                StartCoroutine(DelayedDisconnect(player, 1));
            }
        }
Exemplo n.º 11
0
        private void OnAuthRequestMessage(INetworkPlayer player, AuthRequestMessage msg)
        {
            if (logger.LogEnabled())
            {
                logger.LogFormat(LogType.Log, "Authentication Request: {0} {1}", msg.serverCode);
            }

            // check if client send the same code as the one stored in the server
            if (msg.serverCode == serverCode)
            {
                // create and send msg to client so it knows to proceed
                player.Send(new AuthResponseMessage
                {
                    success = true,
                    message = "Success"
                });

                ServerAccept(player);
            }
            else
            {
                // create and send msg to client so it knows to disconnect
                var authResponseMessage = new AuthResponseMessage
                {
                    success = false,
                    message = "Invalid code"
                };

                ServerReject(player);

                player.Send(authResponseMessage);

                // disconnect the client after 1 second so that response message gets delivered
                StartCoroutine(DelayedDisconnect(player, 1));
            }
        }
Exemplo n.º 12
0
        // executed at the server when we receive a ping message
        // reply with a pong containing the time from the client
        // and time from the server
        internal void OnServerPing(INetworkPlayer player, NetworkPingMessage msg)
        {
            if (logger.LogEnabled())
            {
                logger.Log("OnPingServerMessage  conn=" + player);
            }

            var pongMsg = new NetworkPongMessage
            {
                clientTime = msg.clientTime,
                serverTime = LocalTime()
            };

            player.Send(pongMsg, Channel.Unreliable);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Sets a player as not ready and removes all visible objects
        /// <para>Players that are not ready will not be sent spawn message or state updates.</para>
        /// <para>Players that are not ready do not receive spawned objects or state synchronization updates. They client can be made ready again by calling SetClientReady().</para>
        /// </summary>
        /// <param name="player">The player to make not ready.</param>
        public void SetClientNotReady(INetworkPlayer player)
        {
            ThrowIfNotServer();

            if (player.SceneIsReady)
            {
                if (logger.LogEnabled())
                {
                    logger.Log("PlayerNotReady " + player);
                }
                player.SceneIsReady = false;
                player.RemoveAllVisibleObjects();

                player.Send(new SceneNotReadyMessage());
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Removes the character from a player, with the option to keep the player as the owner of the object
        /// </summary>
        /// <param name="player"></param>
        /// <param name="keepAuthority"></param>
        /// <exception cref="InvalidOperationException">Throws when player does not have a character</exception>
        public void RemoveCharacter(INetworkPlayer player, bool keepAuthority = false)
        {
            ThrowIfNoCharacter(player);

            var identity = player.Identity;

            player.Identity = null;
            if (!keepAuthority)
            {
                logger.Assert(identity.Owner == player, "Owner should be player that is being removed");
                identity.Owner = null;
            }

            player.Send(new RemoveCharacterMessage {
                keepAuthority = keepAuthority
            });
        }
Exemplo n.º 15
0
        internal void SendSpawnMessage(NetworkIdentity identity, INetworkPlayer player)
        {
            if (logger.LogEnabled())
            {
                logger.Log($"Server SendSpawnMessage: name={identity.name} sceneId={identity.SceneId:X} netId={identity.NetId}");
            }

            // one writer for owner, one for observers
            using (PooledNetworkWriter ownerWriter = NetworkWriterPool.GetWriter(), observersWriter = NetworkWriterPool.GetWriter())
            {
                var isOwner = identity.Owner == player;

                var payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter);

                var prefabHash = identity.IsPrefab ? identity.PrefabHash : default(int?);
                var sceneId    = identity.IsSceneObject ? identity.SceneId : default(ulong?);
                var msg        = new SpawnMessage
                {
                    netId         = identity.NetId,
                    isLocalPlayer = player.Identity == identity,
                    isOwner       = isOwner,
                    sceneId       = sceneId,
                    prefabHash    = prefabHash,
                    payload       = payload,
                };

                // values in msg are nullable, so by default they are null
                // only set those values if the identity's settings say to send them
                if (identity.SpawnSettings.SendPosition)
                {
                    msg.position = identity.transform.localPosition;
                }
                if (identity.SpawnSettings.SendRotation)
                {
                    msg.rotation = identity.transform.localRotation;
                }
                if (identity.SpawnSettings.SendScale)
                {
                    msg.scale = identity.transform.localScale;
                }

                player.Send(msg);
            }
        }
Exemplo n.º 16
0
        IEnumerator AddPlayerDelayed(INetworkPlayer player)
        {
            yield return(new WaitForSeconds(.5f));

            player.Send(new SceneMessage {
                scenePath = gameScene, sceneOperation = SceneOperation.LoadAdditive
            });

            PlayerScore playerScore = player.Identity.GetComponent <PlayerScore>();

            playerScore.playerNumber = playerId;
            playerScore.scoreIndex   = playerId / subScenes.Count;
            playerScore.matchIndex   = playerId % subScenes.Count;

            if (subScenes.Count > 0)
            {
                UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(player.Identity.gameObject, subScenes[playerId % subScenes.Count]);
            }

            playerId++;
        }
Exemplo n.º 17
0
        protected internal void SendTargetRpcInternal(INetworkPlayer player, Type invokeClass, string rpcName, NetworkWriter writer, int channelId)
        {
            // this was in Weaver before
            if (Server == null || !Server.Active)
            {
                throw new InvalidOperationException($"RPC Function {rpcName} called when server is not active.");
            }

            // connection parameter is optional. assign if null.
            if (player == null)
            {
                player = ConnectionToClient;
            }

            // This cannot use Server.active, as that is not specific to this object.
            if (!IsServer)
            {
                if (logger.WarnEnabled())
                {
                    logger.LogWarning("ClientRpc " + rpcName + " called on un-spawned object: " + name);
                }
                return;
            }

            // construct the message
            var message = new RpcMessage
            {
                netId          = NetId,
                componentIndex = ComponentIndex,
                // type+func so Inventory.RpcUse != Equipment.RpcUse
                functionHash = RemoteCallHelper.GetMethodHash(invokeClass, rpcName),
                // segment to avoid reader allocations
                payload = writer.ToArraySegment()
            };

            player.Send(message, channelId);
        }
Exemplo n.º 18
0
 internal void HideToPlayer(NetworkIdentity identity, INetworkPlayer player)
 {
     player.Send(new ObjectHideMessage {
         netId = identity.NetId
     });
 }