// A constructor that takes a premade board as its parameter. public GameServer(int port, GameState state, GameServerEventHandlerType aHandler) { this.shutDown = false; this.gameInProgress = false; this.client1Id = -1; this.client2Id = -1; this.connectionCount = 0; this.gameStateUpdateEventHandler = aHandler; this.logic = GameChoice.CurrentGame.GetNewGameLogic(state); this.server = new NetworkServer(port, new NetworkServerEventHandlerType(ServerEventHandler)); }
//Creates a server then returns the port the server is created with. Returns -1 if server is not created private int CreateServer() { int serverPort = -1; //Connect to default port bool serverCreated = NetworkServer.Listen(_broadcastPort); if (serverCreated) { serverPort = _broadcastPort; Debug.Log("Server Created with deafault port"); } else { Debug.Log("Failed to create with the default port"); //Try to create server with other port from min to max except the default port which we trid already for (int tempPort = _minPort; tempPort <= _maxPort; tempPort++) { //Skip the default port since we have already tried it if (tempPort != _broadcastPort) { //Exit loop if successfully create a server if (NetworkServer.Listen(tempPort)) { serverPort = tempPort; break; } //If this is the max port and server is not still created, show, failed to create server error if (tempPort == _maxPort) { Debug.LogError("Failed to create server"); } } } } return(serverPort); }
public void CmdTryPlaceBuilding(int buildingId, Vector3 point) { Building buildingToPlace = null; foreach (Building building in buildings) { if (building.GetId() == buildingId) { buildingToPlace = building; break; } } if (buildingToPlace == null) { return; } if (resources < buildingToPlace.GetPrice()) { return; } BoxCollider buildingCollider = buildingToPlace.GetComponent <BoxCollider>(); if (!CanPlaceBuilding(buildingCollider, point)) { return; } GameObject buildingInstance = Instantiate(buildingToPlace.gameObject, point, buildingToPlace.transform.rotation); NetworkServer.Spawn(buildingInstance, connectionToClient); SetResources(resources - buildingToPlace.GetPrice()); }
public void OnDataReceivedInvalidConnectionIdTest() { // add one custom message handler bool wasReceived = false; NetworkConnection connectionReceived = null; TestMessage1 messageReceived = new TestMessage1(); NetworkServer.RegisterHandler <TestMessage1>((conn, msg) => { wasReceived = true; connectionReceived = conn; messageReceived = msg; }, false); // listen NetworkServer.Listen(1); Assert.That(NetworkServer.connections.Count, Is.EqualTo(0)); // serialize a test message into an arraysegment TestMessage1 testMessage = new TestMessage1 { IntValue = 13, DoubleValue = 14, StringValue = "15" }; NetworkWriter writer = new NetworkWriter(); MessagePacking.Pack(testMessage, writer); ArraySegment <byte> segment = writer.ToArraySegment(); // call transport.OnDataReceived with an invalid connectionId // an error log is expected. LogAssert.ignoreFailingMessages = true; Transport.activeTransport.OnServerDataReceived.Invoke(42, segment, 0); LogAssert.ignoreFailingMessages = false; // message handler should never be called Assert.That(wasReceived, Is.False); Assert.That(connectionReceived, Is.Null); }
public void AddConnectionTest() { // listen NetworkServer.Listen(1); Assert.That(NetworkServer.connections.Count, Is.EqualTo(0)); // add first connection NetworkConnectionToClient conn42 = new NetworkConnectionToClient(42, false, 0); bool result42 = NetworkServer.AddConnection(conn42); Assert.That(result42, Is.True); Assert.That(NetworkServer.connections.Count, Is.EqualTo(1)); Assert.That(NetworkServer.connections.ContainsKey(42), Is.True); Assert.That(NetworkServer.connections[42], Is.EqualTo(conn42)); // add second connection NetworkConnectionToClient conn43 = new NetworkConnectionToClient(43, false, 0); bool result43 = NetworkServer.AddConnection(conn43); Assert.That(result43, Is.True); Assert.That(NetworkServer.connections.Count, Is.EqualTo(2)); Assert.That(NetworkServer.connections.ContainsKey(42), Is.True); Assert.That(NetworkServer.connections[42], Is.EqualTo(conn42)); Assert.That(NetworkServer.connections.ContainsKey(43), Is.True); Assert.That(NetworkServer.connections[43], Is.EqualTo(conn43)); // add duplicate connectionId NetworkConnectionToClient connDup = new NetworkConnectionToClient(42, false, 0); bool resultDup = NetworkServer.AddConnection(connDup); Assert.That(resultDup, Is.False); Assert.That(NetworkServer.connections.Count, Is.EqualTo(2)); Assert.That(NetworkServer.connections.ContainsKey(42), Is.True); Assert.That(NetworkServer.connections[42], Is.EqualTo(conn42)); Assert.That(NetworkServer.connections.ContainsKey(43), Is.True); Assert.That(NetworkServer.connections[43], Is.EqualTo(conn43)); }
public void Cmd_UCE_UnspawnPlaceableObject(NetworkIdentity ni) { if (ni != null) { UCE_PlaceableObject po = ni.GetComponent <UCE_PlaceableObject>(); Entity e = po.GetComponent <Entity>(); if (po && po.pickupable && po.ownerCharacter == this.name ) { //LookAtY(po.gameObject.transform.position); ScriptableItem item; if (ScriptableItem.dict.TryGetValue(po.itemName.GetStableHashCode(), out item)) { // -- enough inventory space? Item result = new Item(item); if (InventoryCanAdd(result, ((UCE_Item_PlaceableObject)item).decreaseAmount)) { // -- delete object from database Database.singleton.UCE_DeletePlaceableObject(this.name, this.guild.name, e.level, po.itemName, po.id); // -- add it back to the inventory again InventoryAdd(new Item(item), ((UCE_Item_PlaceableObject)item).decreaseAmount); // -- remove the object NetworkServer.Destroy(po.gameObject); } } } } }
public override void ServerChangeScene(string newSceneName) { //From menu to game if ("Assets/Scenes/ActiveScenes/" + SceneManager.GetActiveScene().name + ".unity" == menuScene) { for (int i = RoomPlayers.Count - 1; i >= 0; i--) { Debug.Log("Room player number: " + i); var conn = RoomPlayers[i].connectionToClient; var gameplayerInstance = Instantiate(gamePlayerPrefab); if (i == 0) { gameplayerInstance.isLeader = true; } gameplayerInstance.SetDisplayName(RoomPlayers[i].DisplayName); NetworkServer.Destroy(conn.identity.gameObject); NetworkServer.ReplacePlayerForConnection(conn, gameplayerInstance.gameObject, true); GamePlayers.Add(gameplayerInstance); } var RaceModeHUDInstance = Instantiate(RaceModeHUD); var ScoreKeeperInstance = Instantiate(ScoreKeeperPrefab); //These references will only work for the server RaceModeHUDInstance.GetComponent <RaceScoreboard>().networkScoreKeeper = ScoreKeeperInstance.GetComponent <NetworkScoreKeeper>(); ScoreKeeperInstance.GetComponent <NetworkScoreKeeper>().stageTimer = RaceModeHUDInstance.GetComponent <ServerStageTimer>(); ScoreKeeperInstance.GetComponent <NetworkScoreKeeper>().raceScoreboard = RaceModeHUDInstance.GetComponent <RaceScoreboard>(); NetworkServer.Spawn(ScoreKeeperInstance); NetworkServer.Spawn(RaceModeHUDInstance); } base.ServerChangeScene(newSceneName); }
void OnTriggerEnter2D(Collider2D collider) { if (!NetworkServer.active) { return; } AlienInvader hitAlien = collider.gameObject.GetComponent <AlienInvader>(); if (hitAlien != null) { owner.score += hitAlien.score; NetworkServer.Destroy(hitAlien.gameObject); NetworkServer.Destroy(gameObject); } Shield hitShield = collider.gameObject.GetComponent <Shield>(); if (hitShield != null) { NetworkServer.Destroy(hitShield.gameObject); NetworkServer.Destroy(gameObject); } }
/// <summary> /// Add the player using MongoDB. /// </summary> /// <param name="conn">The connection.</param> /// <param name="playerControllerId">The player controller identifier.</param> private void AddPlayerMDB(NetworkConnection conn, short playerControllerId) { NetworkInitializer initializerScript = GetComponent <NetworkInitializer>(); List <Users> users = initializerScript.GetUserList(); // This allows us to initialize all the database data. PlayerInfo playerData = new PlayerInfo(users[_players.Count], initializerScript, playerCount); Debug.Log("Player count: " + _players.Count); Debug.Log("Added User: "******"playerId" + playerCount); // Spawn the player. Vector3 spawnPosition = new Vector3( Convert.ToSingle(playerData.Location.location.x), Convert.ToSingle(playerData.Location.location.y), Convert.ToSingle(playerData.Location.location.z)); Quaternion spawRotation = new Quaternion( Convert.ToSingle(playerData.Location.rotation.x), Convert.ToSingle(playerData.Location.rotation.y), Convert.ToSingle(playerData.Location.rotation.z), Convert.ToSingle(playerData.Location.rotation.w)); // To do set hats and stats? var playerObject = (GameObject)GameObject.Instantiate(playerPrefab, spawnPosition, spawRotation); playerData.SetPlayerObject(playerObject); NetworkServer.AddPlayerForConnection(conn, playerObject, playerControllerId); // Debug.Log("sdfwefwef"); _players.Add(playerCount, playerData); Debug.Log(_players[playerCount].ToString()); playerCount++; }
private static void Postfix(NetworkMessage msg) { var connId = msg.conn.connectionId; if (connId == 0) // ignore local connection { return; } if (!MPTweaks.ClientInfos.TryGetValue(connId, out var clientInfo)) { clientInfo = MPTweaks.ClientCapabilitiesSet(connId, new Dictionary <string, string>()); } /* * if (!clientInfo.SupportsTweaks.Contains("proj") && !MPTweaks.IncompatibleMatchReported) * { * MPTweaks.IncompatibleMatchReported = true; * string name = NetworkMatch.m_players.TryGetValue(connId, out var playerData) ? playerData.m_name : connId.ToString(); * var text = "DISABLED HUNTER SPEED CHANGE! OLD OLMOD: " + name; * Debug.LogFormat("MPTweaks: IncompatibleMatchReported {0}", text); * JIPClientHandlers.SendAddMpStatus(text); * } */ Debug.Log("MPTweaks: conn " + connId + " OnLoadoutDataMessage clientInfo is now " + clientInfo.Capabilities.Join()); if (!MPTweaks.ClientHasMod(connId) && MPTweaks.MatchNeedsMod()) { //LobbyChatMessage chatMsg = new LobbyChatMessage(connId, "SERVER", MpTeam.ANARCHY, "You need OLMOD to join this match", false); //NetworkServer.SendToClient(connId, CustomMsgType.LobbyChatToClient, chatMsg); NetworkServer.SendToClient(connId, 86, new StringMessage("You need OLMOD to join this match.")); GameManager.m_gm.StartCoroutine(DisconnectCoroutine(connId)); } if (clientInfo.Capabilities.ContainsKey("ModPrivateData")) { MPModPrivateDataTransfer.SendTo(connId); } }
public void ConnectDuplicateConnectionIdsTest() { // message handlers NetworkServer.RegisterHandler <ConnectMessage>((conn, msg) => {}, false); NetworkServer.RegisterHandler <DisconnectMessage>((conn, msg) => {}, false); NetworkServer.RegisterHandler <ErrorMessage>((conn, msg) => {}, false); // listen NetworkServer.Listen(2); Assert.That(NetworkServer.connections.Count, Is.EqualTo(0)); // connect first Transport.activeTransport.OnServerConnected.Invoke(42); Assert.That(NetworkServer.connections.Count, Is.EqualTo(1)); NetworkConnectionToClient original = NetworkServer.connections[42]; // connect duplicate - shouldn't overwrite first one Transport.activeTransport.OnServerConnected.Invoke(42); Assert.That(NetworkServer.connections.Count, Is.EqualTo(1)); Assert.That(NetworkServer.connections[42], Is.EqualTo(original)); // shutdown NetworkServer.Shutdown(); }
static internal void OnAnimationTriggerServerMessage(NetworkMessage netMsg) { netMsg.ReadMessage(s_AnimationTriggerMessage); if (LogFilter.logDev) { Debug.Log("OnAnimationTriggerMessage for netId=" + s_AnimationTriggerMessage.netId + " conn=" + netMsg.conn); } GameObject go = NetworkServer.FindLocalObject(s_AnimationTriggerMessage.netId); if (go == null) { return; } NetworkAnimator animSync = go.GetComponent <NetworkAnimator>(); if (animSync != null) { animSync.HandleAnimTriggerMsg(s_AnimationTriggerMessage.hash); NetworkServer.SendToReady(go, MsgType.AnimationTrigger, s_AnimationTriggerMessage); } }
public static bool Prefix(Inventory __instance, ref Pickup __result, ItemType droppedItemId, float dur, Vector3 pos, Quaternion rot, int s, int b, int o) { if (Configs.item_cleanup < 0 || __instance.name == "Host") { return(true); } Log.Debug($"[ItemCleanupPatch] {droppedItemId}{pos} Time:{Time.time} Cleanuptimes:{Configs.item_cleanup}"); if (droppedItemId < ItemType.KeycardJanitor) { __result = null; return(false); } GameObject gameObject = UnityEngine.Object.Instantiate(__instance.pickupPrefab); NetworkServer.Spawn(gameObject); items.Add(gameObject, Time.time); gameObject.GetComponent <Pickup>().SetupPickup(new Pickup.PickupInfo { position = pos, rotation = rot, itemId = droppedItemId, durability = dur, weaponMods = new int[3] { s, b, o }, ownerPlayer = __instance.gameObject }); __result = gameObject.GetComponent <Pickup>(); return(false); }
private void CmdBasicAttack(Vector2 direction) { if (Time.time > nextFire) { nextFire = Time.time + fireRate; GameObject knife = GameObject.Instantiate(knifePrefab);//, transform.position + direction.normalized * 1f, Quaternion.FromToRotation(Vector3.right, new Vector3(direction.x, direction.y, 0))); Quaternion resetRot = Quaternion.identity; resetRot.eulerAngles = new Vector3(0, 0, 0); knife.transform.rotation = resetRot; Quaternion rot = Quaternion.identity; rot.eulerAngles = direction; knife.transform.rotation = Quaternion.FromToRotation(knife.transform.right, new Vector3(direction.x, direction.y, 0)); knife.transform.position = transform.position + (new Vector3(direction.x, direction.y, 0)) * 1f; //un minimo di distanza dal centro dell'octo OctoChefKnife octoKnife = knife.GetComponent <OctoChefKnife>(); octoKnife.inNekoMaidComboField = isInNekoComboField; octoKnife.inFishermanComboField = isInFishermanComboField; octoKnife.damage = m_basic_attack_damage; octoKnife.octoChef = gameObject; octoKnife.enemiesToHit = enemiesHitWithKnife; octoKnife.inNekoMaidComboField = isInNekoComboField; knife.GetComponent <Rigidbody2D>().velocity = knifeVelocity * direction; NetworkServer.Spawn(knife); } }
public void DisconnectAllConnectionsTest() { // message handlers NetworkServer.RegisterHandler <ConnectMessage>((conn, msg) => {}, false); NetworkServer.RegisterHandler <DisconnectMessage>((conn, msg) => {}, false); NetworkServer.RegisterHandler <ErrorMessage>((conn, msg) => {}, false); // listen NetworkServer.Listen(1); Assert.That(NetworkServer.connections.Count, Is.EqualTo(0)); // add connection NetworkConnectionToClient conn42 = new NetworkConnectionToClient(42); NetworkServer.AddConnection(conn42); Assert.That(NetworkServer.connections.Count, Is.EqualTo(1)); // disconnect all connections NetworkServer.DisconnectAllConnections(); Assert.That(NetworkServer.connections.Count, Is.EqualTo(0)); // shutdown NetworkServer.Shutdown(); }
public ServerGameWorld(GameWorld world, NetworkServer networkServer, Dictionary <int, ServerGameLoop.ClientInfo> clients, ChatSystemServer m_ChatSystem, BundledResourceManager resourceSystem) { m_NetworkServer = networkServer; m_Clients = clients; this.m_ChatSystem = m_ChatSystem; m_GameWorld = world; m_CharacterModule = new CharacterModuleServer(m_GameWorld, resourceSystem); m_ProjectileModule = new ProjectileModuleServer(m_GameWorld, resourceSystem); m_HitCollisionModule = new HitCollisionModule(m_GameWorld, 128, 1); m_PlayerModule = new PlayerModuleServer(m_GameWorld, resourceSystem); m_DebugPrimitiveModule = new DebugPrimitiveModule(m_GameWorld, 0.4f, 0.02f); m_SpectatorCamModule = new SpectatorCamModuleServer(m_GameWorld, resourceSystem); m_ReplicatedEntityModule = new ReplicatedEntityModuleServer(m_GameWorld, resourceSystem, m_NetworkServer); m_ReplicatedEntityModule.ReserveSceneEntities(networkServer); m_WeaponsModule = new WeaponsModule(m_GameWorld, resourceSystem, true); m_BonusModule = new BonusModuleServer(m_GameWorld, resourceSystem); m_GameModeSystem = m_GameWorld.GetECSWorld().CreateManager <GameModeSystemServer>(m_GameWorld, m_ChatSystem, resourceSystem); m_DestructablePropSystem = m_GameWorld.GetECSWorld().CreateManager <UpdateDestructableProps>(m_GameWorld); m_DamageAreaSystem = m_GameWorld.GetECSWorld().CreateManager <DamageAreaSystemServer>(m_GameWorld); m_TeleporterSystem = m_GameWorld.GetECSWorld().CreateManager <TeleporterSystemServer>(m_GameWorld); m_HandleGrenadeRequests = m_GameWorld.GetECSWorld().CreateManager <HandleGrenadeRequest>(m_GameWorld, resourceSystem); m_StartGrenadeMovement = m_GameWorld.GetECSWorld().CreateManager <StartGrenadeMovement>(m_GameWorld); m_FinalizeGrenadeMovement = m_GameWorld.GetECSWorld().CreateManager <FinalizeGrenadeMovement>(m_GameWorld); m_platformSystem = m_GameWorld.GetECSWorld().CreateManager <MoverUpdate>(m_GameWorld); m_MoveableSystem = new MovableSystemServer(m_GameWorld, resourceSystem); m_CameraSystem = new ServerCameraSystem(m_GameWorld); }
// stop/disconnect ///////////////////////////////////////////////////////// // called on the server when a client disconnects public override void OnServerDisconnect(NetworkConnection conn) { print("OnServerDisconnect " + conn); // save player (if any) GameObject go = Utils.GetGameObjectFromPlayerControllers(conn.playerControllers); if (go != null) { Database.CharacterSave(go.GetComponent<Player>(), false); print("saved:" + go.name); } else print("no player to save for: " + conn); // addon system hooks Utils.InvokeMany(typeof(NetworkManagerMMO), this, "OnServerDisconnect_", conn); // remove logged in account after everything else was done lobby.Remove(conn); // just returns false if not found // do base function logic without showing the annoying Debug.LogErrror // (until UNET fixes it) //base.OnServerDisconnect(conn); NetworkServer.DestroyPlayersForConnection(conn); }
// Start is called before the first frame update void Start() { this.isServer = GameObject.Find("GameManager").GetComponent <game_controller>().isServer; if (this.isServer == true && this.isLocalPlayer) { NetworkServer.Destroy(this.gameObject); } else { if (this.isLocalPlayer) { this.GetComponentInChildren <Camera>().enabled = true; this.GetComponentInChildren <Canvas>().enabled = true; } } isForward = false; isBack = false; isLeft = false; isRight = false; isFalling = false; jumpSpeed = 200.0f; walkSpeed = 4.25f; }
private static bool Prefix(RagdollManager __instance, Vector3 pos, Quaternion rot, Vector3 velocity, int classId, global::PlayerStats.HitInfo ragdollInfo, bool allowRecall, string ownerID, string ownerNick, int playerId) { Role role = __instance.hub.characterClassManager.Classes.SafeGet(classId); if (role.model_ragdoll == null) { return(false); } var gameObject = Object.Instantiate(role.model_ragdoll, pos + role.ragdoll_offset.position, Quaternion.Euler(rot.eulerAngles + role.ragdoll_offset.rotation)); NetworkServer.Spawn(gameObject); Ragdoll component = gameObject.GetComponent <Ragdoll>(); component.Networkowner = new Ragdoll.Info(ownerID, ownerNick, ragdollInfo, role, playerId); component.NetworkallowRecall = allowRecall; component.NetworkPlayerVelo = velocity; var synapseragdoll = new Synapse.Api.Ragdoll(component); Map.Get.Ragdolls.Add(synapseragdoll); return(false); }
public void StartupHost() { SetServerName(); SetServerIPConfig(); SetServerPortConfig(); string ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9‌​]{2}|2[0-4][0-9]|25[0-5])$"; // IP validation Regex reg = new Regex(ValidIpAddressRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline); Match match = reg.Match(ip); if (!match.Success) { Debug.Log("[GAMESERVER]: Error on Startup Host, please set a valid IP address and PORT number."); } else { NetworkManager.singleton.StartServer(); uiObjects.ServerConfigUI.SetActive(false); // register chat handler on server NetworkServer.RegisterHandler((short)handlersCode.chatCode, uiObjects.ChatUI.GetComponent <PlayerChat>().ServerReceiveMessage); } }
// Token: 0x060011C8 RID: 4552 RVA: 0x00057FEC File Offset: 0x000561EC private void CreateTerminals() { this.terminalGameObjects = new GameObject[this.terminalPositions.Length]; for (int i = 0; i < this.terminalPositions.Length; i++) { PickupIndex newPickupIndex = PickupIndex.none; switch (this.itemTier) { case ItemTier.Tier1: newPickupIndex = Run.instance.availableTier1DropList[Run.instance.treasureRng.RangeInt(0, Run.instance.availableTier1DropList.Count)]; break; case ItemTier.Tier2: newPickupIndex = Run.instance.availableTier2DropList[Run.instance.treasureRng.RangeInt(0, Run.instance.availableTier2DropList.Count)]; break; case ItemTier.Tier3: newPickupIndex = Run.instance.availableTier3DropList[Run.instance.treasureRng.RangeInt(0, Run.instance.availableTier3DropList.Count)]; break; case ItemTier.Lunar: newPickupIndex = Run.instance.availableLunarDropList[Run.instance.treasureRng.RangeInt(0, Run.instance.availableLunarDropList.Count)]; break; } bool newHidden = this.hideDisplayContent && Run.instance.treasureRng.nextNormalizedFloat < 0.2f; GameObject gameObject = UnityEngine.Object.Instantiate <GameObject>(this.terminalPrefab, this.terminalPositions[i].position, this.terminalPositions[i].rotation); this.terminalGameObjects[i] = gameObject; gameObject.GetComponent <ShopTerminalBehavior>().SetPickupIndex(newPickupIndex, newHidden); NetworkServer.Spawn(gameObject); } GameObject[] array = this.terminalGameObjects; for (int j = 0; j < array.Length; j++) { array[j].GetComponent <PurchaseInteraction>().onPurchase.AddListener(new UnityAction <Interactor>(this.DisableAllTerminals)); } }
public virtual void ServerChangeScene(string newSceneName) { if (string.IsNullOrEmpty(newSceneName)) { if (LogFilter.logError) { Debug.LogError("ServerChangeScene empty scene name"); } } else { if (LogFilter.logDebug) { Debug.Log("ServerChangeScene " + newSceneName); } NetworkServer.SetAllClientsNotReady(); networkSceneName = newSceneName; s_LoadingSceneAsync = Application.LoadLevelAsync(newSceneName); StringMessage msg = new StringMessage(networkSceneName); NetworkServer.SendToAll(0x27, msg); s_StartPositionIndex = 0; s_StartPositions.Clear(); } }
private void NetChunkMade(object[] args) { // Called when a player requests a chunk from the server, then the server posts an event that leads here. bool worked = (bool)args[0]; if (!worked) { Debug.LogError("Net chunk creation failed, unknown error."); return; } string data = (string)args[1]; int chunkX = (int)args[2]; int chunkY = (int)args[3]; GameObject player = (GameObject)args[4]; Msg_SendChunk msg = new Msg_SendChunk() { Data = data, ChunkX = chunkX, ChunkY = chunkY, Layer = Name }; // Send the data to the client using the server. NetworkServer.SendToClientOfPlayer(player, (short)MessageTypes.SEND_CHUNK_DATA, msg); }
public IEnumerator ShutDownNetwork() { if (!NetworkServer.active) { Debug.Log("StopClient"); LobbyManager.singleton.StopClient(); } else { Debug.Log("Waiting connections"); while (CheckConnections() > 1) { yield return(null); } Debug.Log("StopHost"); LobbyManager.singleton.StopHost(); LobbyManager.singleton.StopServer(); NetworkServer.DisconnectAll(); } /// StartCoroutine(ExitDelay()); }
// Use this for initialization void Start() { //Check if instance already exists if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } DontDestroyOnLoad(gameObject); //positionHandler = new RandomPositionHandler(); //positionHandler = new CsvFilePositionHandler("positions.csv"); positionHandler = new NetworkPositionHandler(); NetworkServer posServer = new NetworkServer((NetworkPositionHandler)positionHandler); posServer.Start(); SetupObjects(); }
/// <summary> /// General subscene loader /// </summary> /// <param name="sceneName"></param> /// <returns></returns> IEnumerator LoadSubScene(string sceneName, SubsceneLoadTimer loadTimer = null, bool HandlSynchronising = true) { AsyncOperation AO = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive); if (AO == null) { yield break; // Null if scene not found. } while (AO.isDone == false) { if (loadTimer != null) { loadTimer.IncrementLoadBar(); } yield return(WaitFor.EndOfFrame); } if (loadTimer != null) { loadTimer.IncrementLoadBar(); } if (isServer) { NetworkServer.SpawnObjects(); } else { if (HandlSynchronising) { NetworkClient.PrepareToSpawnSceneObjects(); yield return(WaitFor.Seconds(0.2f)); RequestObserverRefresh.Send(sceneName); } } }
static internal void OnAnimationParametersServerMessage(NetworkMessage netMsg) { netMsg.ReadMessage(s_AnimationParametersMessage); if (LogFilter.logDev) { Debug.Log("OnAnimationParametersMessage for netId=" + s_AnimationParametersMessage.netId + " conn=" + netMsg.conn); } GameObject go = NetworkServer.FindLocalObject(s_AnimationParametersMessage.netId); if (go == null) { return; } NetworkAnimator animSync = go.GetComponent <NetworkAnimator>(); if (animSync != null) { NetworkReader reader = new NetworkReader(s_AnimationParametersMessage.parameters); animSync.HandleAnimParamsMsg(s_AnimationParametersMessage, reader); NetworkServer.SendToReady(go, MsgType.AnimationParameters, s_AnimationParametersMessage); } }
private void StartTurnsForPlayers() { if (playerTurn >= lobbyManager.GetParticipatingPlayers().Count&& (GameState.currentState != GameState.PlanningPhase)) { //Time to start Debug.Log("Time to start planning again!"); gameManager.StartPlanningPhase(AceRules.Player_Draw_Count); } else { var player = lobbyManager.GetParticipatingPlayers()[playerTurn]; if ((player.HasBonusCard() && player.HasAttackCard()) || player.HasFaceUpAssassin()) { NetworkServer.SendToClient(playerTurn + 1, AceMsgTypes.BattlePhase_PlayerTurn, new MyNetworkMessage()); playerTurn++; } else { //If the current player doesn't have a bonus card, we'll loop back to this method but go through the next player playerTurn++; StartTurnsForPlayers(); } } }
public void DisconnectMessageHandlerTest() { // message handlers bool disconnectCalled = false; NetworkServer.RegisterHandler <ConnectMessage>((conn, msg) => {}, false); NetworkServer.RegisterHandler <DisconnectMessage>((conn, msg) => { disconnectCalled = true; }, false); NetworkServer.RegisterHandler <ErrorMessage>((conn, msg) => {}, false); // listen NetworkServer.Listen(1); Assert.That(disconnectCalled, Is.False); // connect Transport.activeTransport.OnServerConnected.Invoke(42); Assert.That(disconnectCalled, Is.False); // disconnect Transport.activeTransport.OnServerDisconnected.Invoke(42); Assert.That(disconnectCalled, Is.True); // shutdown NetworkServer.Shutdown(); }
private void ServerState_AssignCards() { Debug.Log("Assigning cards"); isPlaying = false; for (int i = 0; i < gamePlayersList.Count; i++) { CardData[] newCards = deck.GetNextCards(13); if (gamePlayersList[i] is HumanPlayer) { var addCardsMsg = new ServerAddCardsMsg(); addCardsMsg.cardDatas = newCards; NetworkServer.SendToClientOfPlayer(gamePlayersList[i].gameObject, ServerAddCardsMsg.msgID, addCardsMsg); } else if (gamePlayersList[i] is BotPlayer) { gamePlayersList[i].Hand.UpdateCardDatas(newCards); ServerAddReadyHands(); } } ServerEnterGameState(GameState.Assigning, "Assigning cards"); }
private void respawnCustomPlayer(NetworkIdentity playerNetID, GameObject oldCharacter) { NetworkConnection netConn = null; if (playerNetID.clientAuthorityOwner != null) { netConn = playerNetID.clientAuthorityOwner; } else { netConn = playerNetID.connectionToServer; } if (netConn != null) { Transform spawnTranform = null; if (oldCharacter) { spawnTranform = oldCharacter.transform; Debug.Log(spawnTranform.position); } if (spawnTranform == null) { spawnTranform = NetworkLobbyManager.singleton.startPositions[netConn.connectionId]; } Debug.Assert(spawnTranform != null, "Could not find a spawn point for the custom networked character."); GameObject playerObject = GameObject.Instantiate(NetworkLobbyManager.singleton.spawnPrefabs[netConn.connectionId], spawnTranform.position, spawnTranform.rotation, this.transform); for (int i = 0; i < playerObject.transform.GetChildCount(); i++) { playerObject.transform.GetChild(i).position = spawnTranform.position; } m_spawnedCharacter = playerObject; NetworkServer.SpawnWithClientAuthority(playerObject, netConn); } }
public ULocalConnectionToServer(NetworkServer localServer) { this.address = "localServer"; this.m_LocalServer = localServer; }
public void StartServer(NetworkServer.ServerConnectionDelegate _ClientConnectedDelegate, NetworkServer.ServerConnectionDelegate _ClientDisconnectedDelegate) { System.Diagnostics.Debug.Assert( GetServer() == null ); if (m_NetworkMode != NetworkMode.E_NetworkNone) { NetworkServer server = gameObject.AddComponent<NetworkServer>(); server.StartServer(m_NetworkMode, m_ConnectionCountMax, m_ConnectPort, m_ServerName, OnServerStarted, OnServerStopped, _ClientConnectedDelegate, _ClientDisconnectedDelegate); } }
public bool Start() { try { context = new ServerContext(); context.ServerConfig = serverConfig; // Database connection check Logger.Output(this, "Checking database connection.."); context.Css = Config.DatabaseConnectionString; using (MySqlConnection conn = new MySqlConnection(Config.DatabaseConnectionString)) { conn.Open(); if (conn.State == ConnectionState.Open) { Logger.Output(this, "Database connection verified.."); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM settings"; MySqlDataReader dr = cmd.ExecuteReader(); // Load all world settings from the database. while (dr.Read()) { string name, value; name = DatabaseHelper.GetString(dr, "name"); value = DatabaseHelper.GetString(dr, "value"); Logger.Record(this, "Config param: {0}\t= '{1}'", name, value); serverConfig.Add(name, value); } dr.Close(); } else { Logger.Output(this, "Database connection can't be opened!"); throw new InvalidOperationException("Database connection can't be opened."); } } Logger.Output(this, "Creating server components.."); Timer = new Stopwatch(); Timer.Start(); Logger.Output(this, "Hi res timer available: {0}, frequency: {1}.", Stopwatch.IsHighResolution, Stopwatch.Frequency); int result; int.TryParse(serverConfig["turn_duration"], out result); context.TurnDuration = result; int.TryParse(serverConfig["users_allowed"], out result); context.Mpt = new MasterPlayerTable(result, context); // Queues QueueManager qMngr = QueueManager.Singletone; qMngr.CreateQueues(result); // Load all WorldData.xml and Entities.xml data DataManager dMngr = DataManager.Singletone; // Create the zone manager. Logger.Output(this, "Creating zone manager.."); context.ZoneManager = new ZoneManager(context); // Now load all static predefined entities. //Logger.Output(this, "Loading static entities.."); //dMngr.LoadStaticEntities(context.ZoneManager); // Create the game processor for handling messages. Logger.Output(this, "Creating game processor.."); context.GameProcessor = new GameProcessor(context); // Create the chat processor for handling chat and remote commands. Logger.Output(this, "Creating chat processor.."); context.ChatProcessor = new ChatProcessor(context); // Network server Logger.Output(this, "Creating network server.."); NetPeerConfiguration cfg = new NetPeerConfiguration("Asteria"); int.TryParse(context.ServerConfig["client_port"], out result); cfg.Port = result; int.TryParse(context.ServerConfig["users_allowed"], out result); cfg.MaximumConnections = result; int.TryParse(context.ServerConfig["max_transmissionunit"], out result); cfg.MaximumTransmissionUnit = result; int.TryParse(context.ServerConfig["client_timeout_seconds"], out result); cfg.ConnectionTimeout = result; cfg.ReceiveBufferSize = 4095; cfg.EnableMessageType(NetIncomingMessageType.ConnectionApproval); #if DEBUG cfg.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage); #endif IPAddress clientAddress; if (context.ServerConfig.ContainsKey("client_host") && IPAddress.TryParse(context.ServerConfig["client_host"], out clientAddress)) { cfg.LocalAddress = clientAddress; Logger.Output(this, "NetworkServer using network interface: {0}:{1}", cfg.LocalAddress, cfg.Port); } else Logger.Output(this, "Could not parse 'client_host' param, using: {0}:{1}", cfg.LocalAddress, cfg.Port); netServerClient = new NetServer(cfg); Logger.Output(this, "Networking params client: max connections: {0}, MTU: {1}, connection timeout: {2}", cfg.MaximumConnections, cfg.MaximumTransmissionUnit, cfg.ConnectionTimeout); networkServer = new NetworkServer(context, netServerClient); int.TryParse(context.ServerConfig["threadpool_size_T1"], out result); networkServer.Start(result); // Inter server Logger.Output(this, "Creating inter server.."); NetPeerConfiguration cfg2 = new NetPeerConfiguration("InterAsteria"); int.TryParse(serverConfig["inter_port"], out result); cfg2.Port = result; int.TryParse(serverConfig["users_allowed"], out result); cfg2.MaximumConnections = result; int.TryParse(serverConfig["max_transmissionunit"], out result); cfg2.MaximumTransmissionUnit = Math.Min(result, 4095); int.TryParse(serverConfig["client_timeout_seconds"], out result); cfg2.ConnectionTimeout = result; cfg2.ReceiveBufferSize = 4095; cfg2.EnableMessageType(NetIncomingMessageType.ConnectionApproval); #if DEBUG cfg2.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage); #endif // TODO: [LOW] look into WorldConnection disconnects.. cfg2.ConnectionTimeout = 120; IPAddress interAddress; if (serverConfig.ContainsKey("inter_host") && IPAddress.TryParse(serverConfig["inter_host"], out interAddress)) { cfg2.LocalAddress = interAddress; Logger.Output(this, "InterServer using network interface: {0}:{1}", cfg2.LocalAddress, cfg2.Port); } else Logger.Output(this, "Could not parse 'inter_host' param, using: {0}:{1}", cfg2.LocalAddress, cfg2.Port); netServerInter = new NetServer(cfg2); Logger.Output(this, "InterServer params: max connections: {0}, MTU: {1}, ping interval: {2}, timeout delay: {3}", cfg2.MaximumConnections, cfg2.MaximumTransmissionUnit, cfg2.PingInterval, cfg2.ConnectionTimeout); interServer = new InterServer(context, netServerInter); int.TryParse(serverConfig["threadpool_size_T1"], out result); interServer.Start(result); // Client state manager Logger.Output(this, "Creating client state manager.."); csm = new ClientStateManager(context); csm.Start(1); // ClientToServerMessage deserializer Logger.Output(this, "Creating message handler.."); msgHandler = new MessageHandler(context, netServerClient); int.TryParse(context.ServerConfig["threadpool_size_T2"], out result); msgHandler.Start(result); // ClientToServerMessage serializer Logger.Output(this, "Creating message sender.."); msgSender = new MessageSender(context, netServerClient); int.TryParse(context.ServerConfig["threadpool_size_T4"], out result); msgSender.Start(result); // Dal Provider Logger.Output(this, "Creating DAL provider.."); dal = new DalProvider(context); context.Dal = dal; // Character Management, Inter Server, Chat Logger.Output(this, "Creating low priority handler.."); lowPrioHandler = new LowPriorityManager(context); int.TryParse(context.ServerConfig["threadpool_size_T3"], out result); lowPrioHandler.Start(result); // Turn Manager Logger.Output(this, "Creating turn manager.."); turnManager = new TurnManager(context); turnManager.Start(); Logger.Output(this, "Configuration finished in {0} milliseconds!", Timer.ElapsedMilliseconds); Thread.Sleep(500); return true; } catch (Exception ex) { Logger.Output(this, "Configure exception: {0}, stack trace: {1}", ex.Message, ex.StackTrace); } return false; }
void Start() { server = new NetworkServer(); }
public ServerSimpleWrapper(NetworkServer server) { this.m_Server = server; }
public CommandConnection(NetworkServer networkServer, Socket socket) : base(networkServer, socket) { CommandBuilder = ((CommandNetworkServer)networkServer).CommandBuilderFactory.NewCommandBuilder(this); CommandProcessorProvider = ((CommandNetworkServer)networkServer).CommandProcessorProviderFactory.NewCommandProcessorProvider(this); }