Exemplo n.º 1
0
        // ReSharper disable once UnusedMember.Local
        private void SendUdpPacket(int playerId, ServerPacketType serverPacketType, Packet packet)
        {
            packet.WriteLength();
            playersManager.clients[playerId].SendUdpPacket(packet);

            Logger.LogEvent(LoggerSection.Network, $"Sent «{Helpers.GetEnumName(serverPacketType)}» UDP packet to the client {playerId}");
        }
Exemplo n.º 2
0
        private void Reconcile(ClientControllablePlayer clientControllablePlayer, ClientGameSnapshot gameSnapshot)
        {
            ClientControllable clientControllable      = clientControllablePlayer.clientControllable;
            Vector2            incorrectClientPosition = clientControllable.stateSnapshots[gameSnapshot.yourLastProcessedInputId].position;
            Vector2            correctServerPosition   = gameSnapshot.playersInfo[clientControllablePlayer.basePlayer.information.id].position;

            Physics2D.simulationMode = SimulationMode2D.Script;

            // Teleport to server location
            clientControllablePlayer.basePlayer.movable.Teleport(correctServerPosition);
            Physics2D.Simulate(Time.fixedDeltaTime);
            clientControllable.UpdateSnapshotStatePosition(gameSnapshot.yourLastProcessedInputId, clientControllablePlayer.transform.position);

            // Apply not yet processed by server inputs
            for (int inputId = gameSnapshot.yourLastProcessedInputId + 1; inputId <= clientControllable.stateSnapshots.Keys.Max(); inputId++)
            {
                clientControllablePlayer.basePlayer.movable.MoveByPlayerInput(clientControllable.stateSnapshots[inputId].input);
                Physics2D.Simulate(Time.fixedDeltaTime);
                clientControllable.UpdateSnapshotStatePosition(inputId, clientControllablePlayer.transform.position);
            }

            Physics2D.simulationMode = SimulationMode2D.FixedUpdate;

            Logger.LogEvent(LoggerSection.ServerReconciliation, $"Reconciled position with the server position. SnapshotId: {gameSnapshot.id}. YourLastProcessedInputId: {gameSnapshot.yourLastProcessedInputId}. Server position: {correctServerPosition}. Client position: {incorrectClientPosition}.");
        }
        public void SendTcpPacket(ClientPacketType clientPacketType, Packet packet)
        {
            packet.WriteLength();
            tcpConnection.SendPacket(packet);

            Logger.LogEvent(LoggerSection.Network, $"Sent «{Helpers.GetEnumName(clientPacketType)}» TCP packet to the server");
        }
Exemplo n.º 4
0
        public void DisconnectPlayer(int playerId)
        {
            if (!clients.ContainsKey(playerId))
            {
                Logger.LogNotice(LoggerSection.Connection, $"Skipping player {playerId} disconnect, because it is already disconnected");
                return;
            }

            Logger.LogEvent(LoggerSection.Connection, $"{clients[playerId].GetTcpEndPoint()} has disconnected (player {playerId})");

            if (clients[playerId].serverPlayer.remoteControllable.isLobbyHost)
            {
                packetsSender.SendKickedPacket(playerId);
                foreach (int playerIdToRemove in clients.Keys.ToList())
                {
                    RemovePlayerFromGame(playerIdToRemove);
                }

                Logger.LogEvent(LoggerSection.Connection, $"Removed every player, because the host player {playerId} has disconnected");

                // Get ready to accept fresh new players
                if (scenesManager.GetActiveScene() != Scene.Lobby)
                {
                    scenesManager.SwitchScene(Scene.Lobby);
                }
            }
            else
            {
                RemovePlayerFromGame(playerId);
            }
        }
Exemplo n.º 5
0
        public void ProcessSnapshot(ClientGameSnapshot gameSnapshot)
        {
            ProcessPlayersData(gameSnapshot);
            ProcessLobbyGamePhaseData(gameSnapshot);
            ProcessPlayGamePhaseData(gameSnapshot);

            Logger.LogEvent(LoggerSection.GameSnapshots, $"Updated game state with snapshot {gameSnapshot}");
        }
Exemplo n.º 6
0
        public void ProcessPacket(int packetTypeId, Packet packet, bool isTcp)
        {
            string protocolName = isTcp ? "TCP" : "UDP";

            Logger.LogEvent(LoggerSection.Network, $"Received «{Helpers.GetEnumName((ServerPacketType) packetTypeId)}» {protocolName} packet from server");

            packetHandlers[packetTypeId](packet);
        }
Exemplo n.º 7
0
        private void ProcessKickedPacket(Packet packet)
        {
            Action action = () =>
            {
                connectionToServer.Disconnect();
                Logger.LogEvent(LoggerSection.Connection, "Received a kick from server");
            };

            networkSimulation.ReceiveThroughNetwork(action);
        }
Exemplo n.º 8
0
        private void Start()
        {
            Logger.Initialize(new[] { LoggerSection.GameSnapshots, LoggerSection.Network }, true);
            Logger.LogEvent(LoggerSection.Initialization, "Started server initialization");

            scenesManager.Initialize(ScenesInitializationCallback);
            metaMonoBehaviours.Initialize();
            clientConnectionsListener.StartListening();

            scenesManager.LoadScene(Scenes.Lobby);
        }
Exemplo n.º 9
0
        private static void SaveSnapshot(GameSnapshot gameSnapshot)
        {
            gameSnapshots.Add(gameSnapshot.id, gameSnapshot);

            if (gameSnapshots.Count > 1000)
            {
                gameSnapshots.Remove(gameSnapshots.Keys.Min());
            }

            Logger.LogEvent(LoggerSection.GameSnapshots, $"Game snapshot captured {gameSnapshot}");
        }
Exemplo n.º 10
0
        // ReSharper disable once UnusedMember.Local
        private void SendTcpPacketToAll(ServerPacketType serverPacketType, Packet packet)
        {
            packet.WriteLength();

            foreach (Client client in playersManager.clients.Values.ToList())
            {
                client.SendTcpPacket(packet);
            }

            Logger.LogEvent(LoggerSection.Network, $"Sent «{Helpers.GetEnumName(serverPacketType)}» TCP packet to all clients");
        }
        public void StartListening()
        {
            tcpConnectionsListener.Initialize(Port);
            Logger.LogEvent(LoggerSection.Initialization, $"TCP connections listener started. Listening at port {Port}.");

            udpClient.Initialize(Port);
            Logger.LogEvent(LoggerSection.Initialization, $"UDP client started. Listening at port {Port}.");

            var test = metaMonoBehaviours.applicationCallbacks;

            test.ScheduleOnApplicationQuitActions(StopListening);
        }
Exemplo n.º 12
0
        public void Initialize()
        {
            onSceneLoadedActions = new List <Action>();
            sceneLoadRequested   = false;

            mainMenu = FindObjectOfType <MainMenu>();

            if (mainMenu == null)
            {
                Logger.LogEvent(LoggerSection.MainMenu, "Unable to find MainMenu object in a scene");
            }
        }
Exemplo n.º 13
0
        private void ProcessWelcomePacket(Packet packet)
        {
            Action action = () =>
            {
                int myPlayerId = packet.ReadInt();
                connectionToServer.FinishConnection(myPlayerId);

                Logger.LogEvent(LoggerSection.Connection, $"Connected successfully to server. My player id is {myPlayerId}");
            };

            networkSimulation.ReceiveThroughNetwork(action);
        }
Exemplo n.º 14
0
        public void SendUdpPacket(ClientPacketType clientPacketType, Packet packet)
        {
            if (udpConnection == null)
            {
                Logger.LogNotice(LoggerSection.Network, "Unable to send udp packet, because udp connection is down");
                return;
            }

            packet.WriteLength();
            udpConnection.SendPacket(packet);

            Logger.LogEvent(LoggerSection.Network, $"Sent «{Helpers.GetEnumName(clientPacketType)}» UDP packet to the server");
        }
Exemplo n.º 15
0
 public override void Interact(int playerId)
 {
     if (playersLockable.IsPlayerLocked(playerId))
     {
         playersLockable.Remove(playerId);
         Logger.LogEvent(LoggerSection.SecurityPanelViewing, $"Player {playerId} has stopped looking at the security panel");
     }
     else
     {
         playersLockable.Add(playerId);
         Logger.LogEvent(LoggerSection.SecurityPanelViewing, $"Player {playerId} has started looking at the security panel");
     }
 }
Exemplo n.º 16
0
        // ReSharper disable once UnusedMember.Local
        private void SendTcpPacketToAllExceptOne(int ignoredPlayerId, ServerPacketType serverPacketType, Packet packet)
        {
            packet.WriteLength();

            foreach (Client client in playersManager.clients.Values.ToList())
            {
                if (client.playerId == ignoredPlayerId)
                {
                    continue;
                }

                client.SendTcpPacket(packet);
            }

            Logger.LogEvent(LoggerSection.Network, $"Sent «{Helpers.GetEnumName(serverPacketType)}» TCP packet to all clients except ${ignoredPlayerId}");
        }
Exemplo n.º 17
0
        public UdpConnection(ConnectionToServer connectionToServer, MetaMonoBehaviours metaMonoBehaviours, PacketsReceiver packetsReceiver, int localPort)
        {
            this.connectionToServer = connectionToServer;
            this.metaMonoBehaviours = metaMonoBehaviours;
            this.packetsReceiver    = packetsReceiver;

            ipEndPoint = new IPEndPoint(IPAddress.Parse(ConnectionToServer.ServerIP), ConnectionToServer.ServerPort);

            udpClient = new UdpClient(localPort);
            udpClient.Connect(ipEndPoint);
            udpClient.BeginReceive(OnConnection, null);
            Logger.LogEvent(LoggerSection.Connection, "Started listening for udp connections");

            Packet packet = new Packet();

            SendPacket(packet);
            Logger.LogEvent(LoggerSection.Connection, "Sent first empty udp packet to connect with server's udp");
        }
Exemplo n.º 18
0
        public void Disconnect()
        {
            // This check and this variable is needed, because unity is not Closing instantly on Application.Quit();
            if (!IsConnected)
            {
                return;
            }

            IsConnected = false;

            tcpConnection.tcpClient.Close();
            tcpConnection = null;
            udpConnection.CloseConnection();
            udpConnection = null;

            scenesManager.SwitchScene(Scene.MainMenu);
            playersManager.ClearPlayers();

            Logger.LogEvent(LoggerSection.Connection, "Disconnected from the server");
        }
        private void OnConnection(IAsyncResult result)
        {
            TcpClient tcpClient = tcpListener.EndAcceptTcpClient(result);

            Logger.LogEvent(LoggerSection.Network, $"Incoming tcp connection from {tcpClient.Client.RemoteEndPoint}...");

            // Start listening for the next client connection
            tcpListener.BeginAcceptTcpClient(OnConnection, null);

            for (int playerId = Game.PlayersManager.MinPlayerId; playerId <= Game.PlayersManager.MaxPlayerId; playerId++)
            {
                // If this client exists already - skip this playerId in order to find a free one
                if (playersManager.clients.ContainsKey(playerId))
                {
                    continue;
                }

                playersManager.clients[playerId] = new Client(playerId, udpClient, packetsReceiver, packetsSender, playersManager, metaMonoBehaviours);
                playersManager.clients[playerId].ConnectTcp(tcpClient);
                return;
            }

            Logger.LogError(LoggerSection.Connection, $"{tcpClient.Client.RemoteEndPoint} failed to connect a client: Server is full");
        }
Exemplo n.º 20
0
        public Dictionary <int, int> GeneratePlayersData(int playerId)
        {
            if (!playersLockable.IsPlayerLocked(playerId))
            {
                Logger.LogError(LoggerSection.AdminPanelViewing, $"Unable to generate admin panel information for player {playerId}, because he is not viewing it right now");
                return(null);
            }

            Dictionary <int, int> adminPanelData = new Dictionary <int, int>();

            foreach (KeyValuePair <int, List <int> > playerIdsInRoom in playerIdsInRooms)
            {
                if (playerIdsInRoom.Value.Count == 0)
                {
                    continue;
                }

                adminPanelData[playerIdsInRoom.Key] = playerIdsInRoom.Value.Count;
            }

            Logger.LogEvent(LoggerSection.AdminPanelViewing, $"Generated admin panel data for player {playerId}");

            return(adminPanelData);
        }
Exemplo n.º 21
0
 public void ConnectToLobby()
 {
     Logger.LogEvent(LoggerSection.Connection, "Connecting to a server");
     connectionToServer.Connect();
     metaMonoBehaviours.applicationCallbacks.ScheduleOnApplicationQuitActions(OnApplicationQuit);
 }