private void OnGetTitleData(NetworkConnection connection, GetTitleDataResult result) { //Do something cool with title data and Return back to the client. var output = string.Format("Recieved {0} Title Data Keys", result.Data.Keys.Count); Logger.Dispatch(LoggerTypes.Info, output); connection.Send(1002, new StringMessage() { value = string.Format(output) }); }
public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) { // check MaxPlayersPerConnection int numPlayersForConnection = 0; foreach (var player in conn.playerControllers) { if (player.IsValid) numPlayersForConnection += 1; } if (numPlayersForConnection >= maxPlayersPerConnection) { if (LogFilter.logWarn) { Debug.LogWarning("NetworkLobbyManager no more players for this connection."); } var errorMsg = new EmptyMessage(); conn.Send(MsgType.LobbyAddPlayerFailed, errorMsg); return; } byte slot = FindSlot(); if (slot == Byte.MaxValue) { if (LogFilter.logWarn) { Debug.LogWarning("NetworkLobbyManager no space for more players"); } var errorMsg = new EmptyMessage(); conn.Send(MsgType.LobbyAddPlayerFailed, errorMsg); return; } var newLobbyGameObject = OnLobbyServerCreateLobbyPlayer(conn, playerControllerId); if (newLobbyGameObject == null) { newLobbyGameObject = (GameObject)Instantiate(playerPrefab.gameObject, Vector3.zero, Quaternion.identity); } var newLobbyPlayer = newLobbyGameObject.GetComponent<CaptainsMessPlayer>(); newLobbyPlayer.slot = slot; lobbySlots[slot] = newLobbyPlayer; NetworkServer.AddPlayerForConnection(conn, newLobbyGameObject, playerControllerId); }
public override void OnClientAuthenticate(NetworkConnection conn) { string precheckStatus; if (!PrecheckTicket(out precheckStatus)) { logger.LogFormat(LogType.Error, "Ticket failed pre-check: {0} for {1}", precheckStatus, ticketString); conn.isAuthenticated = false; // disconnect the client - doing it synchronously hangs! StartCoroutine(DelayedDisconnect(conn, 0.01f)); return; } clientStatus = "Checking ticket"; // proceed AuthRequestMessage authRequestMessage = new AuthRequestMessage { ticketString = ticketString }; conn.Send(authRequestMessage); }
/// <summary> /// Call when a client connects /// </summary> /// <param name="conn"></param> internal static void OnServerAddClient(NetworkConnection conn) { //Sent to client the server config conn.Send(TCNetworkManager.Instance.serverConfig); //Lets just hope our transport never assigns the first connection max value of int if (closeServerOnFirstClientDisconnect && firstConnectionId == int.MaxValue) { firstConnectionId = conn.connectionId; } Logger.Info( "Client from '{Address}' connected with the connection ID of {ConnectionID}.", conn.address, conn.connectionId); IUser user = netManager.tcAuthenticator.GetAccount(conn.connectionId); if (user != null) { ServerChat.SendChatMessage("<b>Join</b>", user.UserName); } }
public override void OnServerAddPlayer(NetworkConnection conn) { base.OnServerAddPlayer(conn); if (GameStarted) { return; } Player p = conn.identity.GetComponent <Player>(); p.Name = "Player"; ResendGameInfoData(conn); if (Admin == null) { Admin = p; conn.Send(new MessageGameStatus { GameStarted = false, Admin = conn.identity.gameObject }); } }
// ------------------------------------------------------------------------------- // RequestUserRegister // @Client // ------------------------------------------------------------------------------- /// <summary> /// Protected override function <c>RequestUserRegister</c> that returns a boolean. /// Sends a user registration request to the server. /// Checks whether the user register request is valid and can be sent to the server. /// Returns a boolean detailing whether the request was sent or not. /// </summary> /// <param name="conn"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="usermail"></param> /// <returns> Returns a boolean detailing whether the request was sent to the server. </returns> protected override bool RequestUserRegister(NetworkConnection conn, string userName, string password, string usermail) { if (!base.RequestUserRegister(conn, userName, password, usermail)) { return(false); } ClientMessageRequestUserRegister message = new ClientMessageRequestUserRegister { username = userName, password = Tools.GenerateHash(name, password), email = usermail, deviceid = Tools.GetDeviceId }; conn.Send(message); debug.LogFormat(this.name, nameof(RequestUserRegister), conn.Id(), userName); //DEBUG return(true); }
// ------------------------------------------------------------------------------- // RequestUserChangePassword // @Client // ------------------------------------------------------------------------------- protected override bool RequestUserChangePassword(NetworkConnection conn, string userName, string oldpassword, string newpassword) { if (!base.RequestUserChangePassword(conn, userName, oldpassword, newpassword)) { return(false); } ClientMessageRequestUserChangePassword message = new ClientMessageRequestUserChangePassword { username = name, oldPassword = Tools.GenerateHash(userName, oldpassword), newPassword = Tools.GenerateHash(userName, newpassword) }; // reset player prefs on password change PlayerPrefs.SetString(Constants.PlayerPrefsPassword, ""); conn.Send(message); return(true); }
IEnumerator AddPlayerDelayed(NetworkConnection conn) { yield return(new WaitForSeconds(.5f)); conn.Send(new SceneMessage { scenePath = gameScene, sceneOperation = SceneOperation.LoadAdditive }); PlayerScore playerScore = conn.Identity.GetComponent <PlayerScore>(); playerScore.playerNumber = playerId; playerScore.scoreIndex = playerId / subScenes.Count; playerScore.matchIndex = playerId % subScenes.Count; if (subScenes.Count > 0) { UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(conn.Identity.gameObject, subScenes[playerId % subScenes.Count]); } playerId++; }
IEnumerator AddPlayerDelayed(NetworkConnection conn) { yield return(new WaitForSeconds(.5f)); conn.Send(new SceneMessage { sceneName = gameScene, sceneOperation = SceneOperation.LoadAdditive }); base.OnServerAddPlayer(conn); PlayerScore playerScore = conn.identity.GetComponent <PlayerScore>(); playerScore.playerNumber = conn.connectionId; playerScore.scoreIndex = conn.connectionId / subScenes.Count; playerScore.matchIndex = conn.connectionId % subScenes.Count; if (subScenes.Count > 0) { SceneManager.MoveGameObjectToScene(conn.identity.gameObject, subScenes[conn.connectionId % subScenes.Count]); } }
// ------------------------------------------------------------------------------- // OnClientMessageRequestPlayerDelete // @Client -> @Server // ------------------------------------------------------------------------------- void OnClientMessageRequestPlayerDelete(NetworkConnection conn, ClientMessageRequestPlayerDelete msg) { ServerMessageResponsePlayerDelete message = new ServerMessageResponsePlayerDelete { success = true, text = "", causesDisconnect = false }; if (DatabaseManager.singleton.TryPlayerDeleteSoft(msg.playername, msg.username)) { message.text = systemText.playerDeleteSuccess; } else { message.text = systemText.playerDeleteFailure; message.success = false; } conn.Send(message); }
// ------------------------------------------------------------------------------- // RequestChangePasswordUser // ------------------------------------------------------------------------------- public override bool RequestChangePasswordUser(NetworkConnection conn, string name, string oldpassword, string newpassword) { if (!base.RequestChangePasswordUser(conn, name, oldpassword, newpassword)) { return(false); } UserChangePasswordRequestMessage message = new UserChangePasswordRequestMessage { username = name, oldPassword = GenerateHash(name, oldpassword), newPassword = GenerateHash(name, newpassword) }; // reset player prefs on password change PlayerPrefs.SetString(Constants.PlayerPrefsPassword, ""); conn.Send(message); return(true); }
// ------------------------------------------------------------------------------- // OnClientMessageRequestUserChangePassword // @Client -> @Server // ------------------------------------------------------------------------------- void OnClientMessageRequestUserChangePassword(NetworkConnection conn, ClientMessageRequestUserChangePassword msg) { ServerMessageResponseUserChangePassword message = new ServerMessageResponseUserChangePassword { success = true, text = "", causesDisconnect = false }; if (DatabaseManager.singleton.TryUserChangePassword(msg.username, msg.oldPassword, msg.newPassword)) { message.text = systemText.userChangePasswordSuccess; } else { message.text = systemText.userChangePasswordFailure; message.success = false; } conn.Send(message); }
// ------------------------------------------------------------------------------- // OnUserChangePasswordRequestMessage // @Client -> @Server // ------------------------------------------------------------------------------- void OnUserChangePasswordRequestMessage(NetworkConnection conn, UserChangePasswordRequestMessage msg) { ServerResponseMessage message = new ServerResponseMessage { code = successCode, text = "", causesDisconnect = true }; if (DatabaseManager.singleton.TryUserChangePassword(msg.username, msg.oldPassword, msg.newPassword)) { message.text = systemText.userChangePasswordSuccess; } else { message.text = systemText.userChangePasswordFailure; message.code = errorCode; } conn.Send(message); }
// ------------------------------------------------------------------------------- // OnClientMessageRequestPlayerSwitchServer // Direction: @Client -> @Server // Execution: @Server // ------------------------------------------------------------------------------- void OnClientMessageRequestPlayerSwitchServer(NetworkConnection conn, ClientMessageRequestPlayerSwitchServer msg) { ServerMessageResponsePlayerSwitchServer message = new ServerMessageResponsePlayerSwitchServer { success = true, text = "", causesDisconnect = false }; if (DatabaseManager.singleton.TryPlayerSwitchServer(msg.playername, msg.anchorname, msg.zonename, msg.token)) { message.text = systemText.playerSwitchServerSuccess; } else { message.text = systemText.playerSwitchServerFailure; message.success = false; } conn.Send(message); }
// ------------------------------------------------------------------------------- // OnClientMessageRequestUserConfirm // @Client -> @Server // ------------------------------------------------------------------------------- /// <summary> /// Event <c>OnClientMessageRequestUserConfirm</c>. /// Triggered by the server receiving a user confirmation request from the client. /// </summary> /// <param name="conn"></param> /// <param name="msg"></param> void OnClientMessageRequestUserConfirm(NetworkConnection conn, ClientMessageRequestUserConfirm msg) { ServerMessageResponseUserConfirm message = new ServerMessageResponseUserConfirm { success = true, text = "", causesDisconnect = false }; if (!GetIsUserLoggedIn(msg.username) && DatabaseManager.singleton.TryUserConfirm(msg.username, msg.password)) { message.text = systemText.userConfirmSuccess; } else { message.text = systemText.userConfirmFailure; message.success = false; } conn.Send(message); }
void OnServerLeaveMatch(NetworkConnection conn, Guid matchId) { if (!NetworkServer.active) { return; } MatchInfo matchInfo = openMatches[matchId]; matchInfo.players--; openMatches[matchId] = matchInfo; PlayerInfo playerInfo = playerInfos[conn]; playerInfo.ready = false; playerInfo.matchId = Guid.Empty; playerInfos[conn] = playerInfo; foreach (KeyValuePair <Guid, HashSet <NetworkConnection> > kvp in matchConnections) { kvp.Value.Remove(conn); } HashSet <NetworkConnection> connections = matchConnections[matchId]; PlayerInfo[] infos = connections.Select(playerConn => playerInfos[playerConn]).ToArray(); foreach (NetworkConnection playerConn in matchConnections[matchId]) { playerConn.Send(new ClientMatchMessage { clientMatchOperation = ClientMatchOperation.UpdateRoom, playerInfos = infos }); } SendMatchList(); conn.Send(new ClientMatchMessage { clientMatchOperation = ClientMatchOperation.Departed }); }
public override void OnServerAddPlayer(NetworkConnection conn) { if (modoServidor == ServidorPartida) { if (SceneManager.GetActiveScene().path == lobbyScene && rondaAJugar <= maxRondas) { RoomPlayer roomPlayerInstance = Instantiate(roomPlayerPrefab); if (indexColoresServidor < maxPlayers) { PlayerColorMessage msg = new PlayerColorMessage(); msg.Color = coloresServidor[indexColoresServidor]; indexColoresServidor++; conn.Send <PlayerColorMessage>(msg); } NetworkServer.AddPlayerForConnection(conn, roomPlayerInstance.gameObject); // Esto se encarga de spawnearlo en todos los clientes también RoomPlayers.Add(roomPlayerInstance); if ((numPlayers == maxPlayers && rondaAJugar < maxRondas) || (numPlayers == maxPlayers / 2 && rondaAJugar == maxRondas)) { NextRound(); } } } else if (modoServidor == ServidorCombate) { if (SceneManager.GetActiveScene().path == lobbyScene) { RoomPlayer roomPlayerInstance = Instantiate(roomPlayerPrefab); NetworkServer.AddPlayerForConnection(conn, roomPlayerInstance.gameObject); // Esto se encarga de spawnearlo en todos los clientes también RoomPlayers.Add(roomPlayerInstance); if (numPlayers == maxPlayers) { StartGame(); } } } }
/// <summary> /// Creates a new game room. /// </summary> /// <param name="playerConnection">The network connection of the player requesting the creation of a game room.</param> /// <param name="msg">The network message containing the information of the game room to create.</param> protected virtual void CreateGameRoom(NetworkConnection playerConnection, RequestCreateGameRoomMessage msg) { var zoneServer = SelectZoneServer(); if (zoneServer != null) { ConnectToZoneServer(zoneServer.ip, zoneServer.port) .Then(client => { awaitingPlayerConnections.Add(playerConnection); msg.playerConnectionId = playerConnection.connectionId; return(RequestCreateGameRoom(client, msg)); }) .Then(responseSpawnGameServerMessage => { if (!responseSpawnGameServerMessage.success) { var connection = awaitingPlayerConnections.Find(x => x.connectionId == responseSpawnGameServerMessage.playerConnectionId); if (connection != null) { var responseMsg = new ResponseCreateGameRoomMessage(); responseMsg.success = false; connection.Send(GameRoomsNetworkProtocol.ResponseCreateGameRoom, responseMsg); awaitingPlayerConnections.Remove(connection); } } }) .Catch(e => { Debug.Log(e.Message); }); } else { var responseMsg = new ResponseCreateGameRoomMessage(); responseMsg.success = false; responseMsg.error = CreateGameRoomError.ZoneServerUnavailable; playerConnection.Send(GameRoomsNetworkProtocol.ResponseCreateGameRoom, responseMsg); } }
public void SendTo(GameObject recipient) { if (recipient == null) { return; } NetworkConnection connection = recipient.GetComponent <NetworkIdentity>().connectionToClient; // only send to players that are currently controlled by a client if (PlayerList.Instance.ContainsConnection(connection)) { connection.Send(GetMessageType(), this); Logger.LogTraceFormat("SentTo {0}: {1}", Category.NetMessage, recipient.name, this); } else { Logger.LogTraceFormat("Not sending message {0} to {1}", Category.NetMessage, this, recipient.name); } //Obsolete version: //NetworkServer.SendToClientOfPlayer(recipient, GetMessageType(), this); }
public async Task ShouldTriggerConnectionTerminatedWhenSending() { NetworkDirection direction = NetworkDirection.Outgoing; using (NetworkFixture fixture = new NetworkFixture()) using (TcpSocket host = fixture.Pool.New()) using (TcpSocket socket = fixture.Pool.New()) { TcpSocketInfo info = host.BindAndInfo(); int port = info.Endpoint.Port; IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port); socket.Bind(); host.Listen(10); Task <TcpSocketAccept> task = host.Accept(); TcpSocketConnect connect = await socket.Connect(endpoint); TcpSocketAccept accept = await task; connect.Status.Should().Be(SocketStatus.OK); accept.Status.Should().Be(SocketStatus.OK); accept.Connection.Dispose(); NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint); Trigger handler = Trigger.Bind(ref fixture.Hooks.OnConnectionTerminated, data => { data.Remote.Should().Be(NetworkAddress.Parse(endpoint)); data.Connection.Should().NotBeNull(); }); for (int i = 0; i < 10; i++) { connection.Send(new OneByteMessage()); } handler.Wait().Should().BeTrue(); } }
// ------------------------------------------------------------------------------- // OnPlayerSwitchServerRequestMessage // @Client -> @Server // ------------------------------------------------------------------------------- void OnPlayerSwitchServerRequestMessage(NetworkConnection conn, PlayerSwitchServerRequestMessage msg) { ServerResponseMessage message = new ServerResponseMessage { code = successCode, text = "", causesDisconnect = false }; if (DatabaseManager.singleton.TryPlayerSwitchServer(msg.username, msg.token)) { message.text = systemText.playerSwitchServerSuccess; eventListener.onPlayerSwitchServer.Invoke(msg.username); } else { message.text = systemText.playerSwitchServerFailure; message.code = errorCode; } conn.Send(message); }
// ------------------------------------------------------------------------------- // OnUserConfirmRequestMessage // @Client -> @Server // ------------------------------------------------------------------------------- void OnUserConfirmRequestMessage(NetworkConnection conn, UserConfirmRequestMessage msg) { ServerResponseMessage message = new ServerResponseMessage { code = successCode, text = "", causesDisconnect = false }; if (DatabaseManager.singleton.TryUserConfirm(msg.username, msg.password)) { message.text = systemText.userConfirmSuccess; eventListener.onUserConfirm.Invoke(msg.username); } else { message.text = systemText.userConfirmFailure; message.code = errorCode; } conn.Send(message); }
// ======================= PUBLIC METHODS - PLAYER ================================ // ------------------------------------------------------------------------------- // RequestPlayerLogin // @Client // ------------------------------------------------------------------------------- /// <summary> /// Protected override function <c>RequestPlayerLogin</c> that returns a boolean. /// Sends a player login request to the server. /// Checks whether the player login request is valid and can be sent to the server. /// Returns a boolean detailing whether the request was sent or not. /// </summary> /// <param name="conn"></param> /// <param name="playername"></param> /// <param name="username"></param> /// <returns> Returns a boolean detailing whether the request was sent to the server. </returns> protected override bool RequestPlayerLogin(NetworkConnection conn, string playername, string username) { if (!base.RequestPlayerLogin(conn, playername, username)) { return(false); } ClientMessageRequestPlayerLogin message = new ClientMessageRequestPlayerLogin { playername = playername, username = username }; // must be readied here, not in the response - otherwise it generates a warning ClientScene.Ready(conn); conn.Send(message); debug.LogFormat(this.name, nameof(RequestPlayerLogin), conn.Id(), username, playername); //DEBUG return(true); }
public override void OnClientAuthenticate(NetworkConnection conn) { // send login packet with hashed password, so that the original one // never leaves the player's computer. // // it's recommended to use a different salt for each hash. ideally we // would store each user's salt in the database. to not overcomplicate // things, we will use the account name as salt (at least 16 bytes) // // Application.version can be modified under: // Edit -> Project Settings -> Player -> Bundle Version string hash = Utils.PBKDF2Hash(loginPassword, passwordSalt + loginAccount); LoginMsg message = new LoginMsg { account = loginAccount, password = hash, version = Application.version }; conn.Send(message); print("login message was sent"); // set state manager.state = NetworkState.Handshake; }
public void SendDataIfReady(ref NetworkConnection connection, ref UdpNetworkDriver driver, List <PersistentPlayerInfo> allPlayerInfo) { if (sendQueue == null) { return; } // Heart beat every once in a while to prevent disconnects for no reason if (timeSinceLastHeartBeat * 1000 + heartbeatFrequencyMs <= Time.time * 1000) { timeSinceLastHeartBeat = Time.time; sendQueue.Enqueue((byte)LOBBY_CLIENT_REQUESTS.HEARTBEAT); } // Not time to send yet. if (timeSinceLastSend * 1000 + sendFrequencyMs > Time.time * 1000) { return; } timeSinceLastSend = Time.time; if (sendQueue.Count <= 0 || driver.GetConnectionState(connection) != NetworkConnection.State.Connected) { return; } // Send eveyrthing in the queue using (var writer = new DataStreamWriter(sendQueue.Count, Allocator.Temp)) { while (sendQueue.Count > 0) { writer.Write(sendQueue.Dequeue()); } connection.Send(driver, writer); } }
public override void OnClientConnect(NetworkConnection conn) { base.OnClientConnect(conn); Debug.Log("Connected to server!"); if (ConnectionEstablished != null) { ConnectionEstablished(); } AddHybridPlayerMessage msg = new AddHybridPlayerMessage(); msg.playerControllerId = 0; msg.PlayerType = Utils.CurrentPlayerType; if (msg.PlayerType == Utils.PlayerType.HoloLens) { msg.AlignmentPosition = markerTransform.position; msg.AlignmentRotation = alignmentYRotation; } conn.Send(CustomMsgType.AddHybridPlayer, msg); }
// ======================== MESSAGE HANDLERS - PLAYER ============================ // ------------------------------------------------------------------------------- // OnClientMessageRequestPlayerAutoLogin // Direction: @Client -> @Server // Execution: @Server // ------------------------------------------------------------------------------- void OnClientMessageRequestPlayerAutoLogin(NetworkConnection conn, ClientMessageRequestPlayerAutoLogin msg) { ServerMessageResponsePlayerAutoLogin message = new ServerMessageResponsePlayerAutoLogin { success = true, text = "", causesDisconnect = false }; if (DatabaseManager.singleton.TryPlayerAutoLogin(msg.playername, msg.username)) { AutoLoginPlayer(conn, msg.username, msg.playername, msg.token); message.text = systemText.playerLoginSuccess; } else { message.text = systemText.playerLoginFailure; message.success = false; } conn.Send(message); }
/// <summary> /// 链接成功的客户端回调 /// </summary> /// <param name="conn"></param> public override void OnClientConnect(NetworkConnection conn) { print("OnClientConnect"); // setup handlers // the following workaround was needed to avoid a exception in Unity 5.2 //var client = NetworkClient.allClients[0]; <- not needed in 5.3 anymore client.RegisterHandler(CharactersAvailableMsg.MsgId, OnClientCharactersAvailable); client.RegisterHandler(ErrorMsg.MsgId, OnClientReceivePopup); // send login packet var msg = new LoginMsg(); msg.id = id; msg.pw = pw; conn.Send(LoginMsg.MsgId, msg); print("login msg was sent"); // call base function to make sure that client becomes "ready" //base.OnClientConnect(conn); ClientScene.Ready(conn); // from bitbucket OnClientConnect source }
// ------------------------------------------------------------------------------- // OnClientMessageRequestUserRegister // @Client -> @Server // ------------------------------------------------------------------------------- void OnClientMessageRequestUserRegister(NetworkConnection conn, ClientMessageRequestUserRegister msg) { ServerMessageResponseUserRegister message = new ServerMessageResponseUserRegister { success = true, text = "", causesDisconnect = false }; if (DatabaseManager.singleton.TryUserRegister(msg.username, msg.password, msg.email, msg.deviceid)) { DatabaseManager.singleton.SaveDataUser(msg.username, false); message.text = systemText.userRegisterSuccess; } else { message.text = systemText.userRegisterFailure; message.success = false; } conn.Send(message); }
public void ResendGameInfoData(NetworkConnection conn = null) { MessageGameInfo info = new MessageGameInfo { VictimVision = VictimVision, VictimLives = VictimLives, VictimSpeed = VictimSpeed, HunterVision = HunterVision, HunterKillCooldown = HunterKillCooldown, HunterSpeed = HunterSpeed, Hunters = Hunters, DisplayHunters = DisplayHunters, VictimTaskDistance = VictimTaskDistance, HunterKillDistance = HunterKillDistance, HunterVisionOnCooldown = HunterVisionOnCooldown, VictimCommonTasks = VictimCommonTasks, VictimLongTasks = VictimLongTasks, VictimShortTasks = VictimShortTasks, TimeLimit = TimeLimit, DefaultColor = DefaultColor, TasksBalancedDamage = TasksBalancedDamage }; if (NetworkServer.active) { if (conn != null) { conn.Send(info); } else { NetworkServer.SendToAll(info); } } else { NetworkClient.Send(info); } }
public void SendDataIfReady(ref NetworkConnection connection, ref UdpNetworkDriver driver, Dictionary <int, ObjectWithDelta> IdToClientControlledObjectDictionary) { CreateQueueIfNecessary(); // Heart beat every once in a while to prevent disconnects if (timeSinceLastHeartBeat * 1000 + heartbeatFrequencyMs <= Time.time * 1000) { timeSinceLastHeartBeat = Time.time; sendQueue.Enqueue((byte)GAME_CLIENT_REQUESTS.HEARTBEAT); } // Not time to send yet. if (timeSinceLastSend * 1000 + sendFrequencyMs > Time.time * 1000) { return; } timeSinceLastSend = Time.time; HandleObjectDiff(IdToClientControlledObjectDictionary); if (sendQueue.Count <= 0) { return; } // Send eveyrthing in the queue using (var writer = new DataStreamWriter(sendQueue.Count, Allocator.Temp)) { while (sendQueue.Count > 0) { writer.Write(sendQueue.Dequeue()); } connection.Send(driver, writer); } }
public async void OnAuthRequestMessage(NetworkConnection conn, AuthRequestMessage msg) { bool isValid = await loginService.Validate(msg.accessToken); if (!isValid) { StartCoroutine(DelayedDisconnect(conn, "Invalid access token.")); return; } Jwt jwt = new Jwt(msg.accessToken); string[] allowedUserIds = GameState.singleton.gameServerModel.allowedUserIds; if (allowedUserIds.Length > 0 && !allowedUserIds.Contains(jwt.payload.user._id)) { StartCoroutine(DelayedDisconnect(conn, "User not allowed.")); return; } Debug.Log("User is allowed."); // Set authenticationData for other scripts to use. GroupModel groupModel = await GetGroupModel(msg.groupId, jwt.payload.user._id); conn.authenticationData = new AuthenticationData { groupModel = groupModel, userModel = jwt.payload.user }; // Create and send msg to client so it knows to proceed. AuthResponseMessage authResponseMessage = new AuthResponseMessage { code = 200, message = "Success" }; conn.Send(authResponseMessage); OnServerAuthenticated.Invoke(conn); }
public void KickPlayer(NetworkConnection conn) { conn.Send(MsgKicked, new KickMsg()); }
public override void OnServerConnect(NetworkConnection conn) { conn.Send(MyMsgType.UpdateSeed, new StringMessage(GameController.seed)); base.OnServerConnect(conn); }
public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId) { //UIConsole.Log ("OnServerAddPlayer " + Application.loadedLevelName); if (CheckIfLobbyScene ()) { base.OnServerAddPlayer (conn, playerControllerId); if(_lobbyInfo!=null) NetworkServer.Destroy(_lobbyInfo.gameObject); _lobbyInfo = ((GameObject)Instantiate(lobbyInfoPrefab)).GetComponent<LobbyPlayerInfo>(); NetworkServer.Spawn(_lobbyInfo.gameObject); } else { int num = 0; foreach (PlayerController current in conn.playerControllers) { if (current.IsValid) { num++; } } if (num > this.maxPlayersPerConnection) { UnityEngine.Networking.NetworkSystem.EmptyMessage msg = new UnityEngine.Networking.NetworkSystem.EmptyMessage (); conn.Send (45, msg); return; } if(resetSpawnPointsOnSceneChange) { GameObject.Find("RespawnManager").GetComponent<RespawnPointsManager>().SetupInitialSpawnPoints(); resetSpawnPointsOnSceneChange = false; } Vector3 spawnPos = GameObject.Find("RespawnManager").GetComponent<RespawnPointsManager>().GetInitialSpawnPoint(); //UIConsole.Log()); GameObject player = (GameObject)Object.Instantiate(onlinePlayerPrefab,spawnPos,Quaternion.identity); NetworkServer.AddPlayerForConnection(conn,player,playerControllerId); //UIConsole.Log("FAILED TO ADD PLAYER"); } }