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"); }
// 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}"); }
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); } }
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 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); }
public void ProcessSnapshot(ClientGameSnapshot gameSnapshot) { ProcessPlayersData(gameSnapshot); ProcessLobbyGamePhaseData(gameSnapshot); ProcessPlayGamePhaseData(gameSnapshot); Logger.LogEvent(LoggerSection.GameSnapshots, $"Updated game state with snapshot {gameSnapshot}"); }
private void UpdateLastProcessedInputId(PlayerInput playerInput) { if (lastProcessedInputId >= playerInput.id) { Logger.LogError(LoggerSection.GameSnapshots, $"Got less or equal last inputId. Last remembered: {lastProcessedInputId}, new: {playerInput.id}"); return; } lastProcessedInputId = playerInput.id; }
private void ProcessKickedPacket(Packet packet) { Action action = () => { connectionToServer.Disconnect(); Logger.LogEvent(LoggerSection.Connection, "Received a kick from server"); }; networkSimulation.ReceiveThroughNetwork(action); }
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); }
// 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 SendPacket(Packet packet, IPEndPoint ipEndPoint) { try { udpClient.BeginSend(packet.ToArray(), packet.GetLength(), ipEndPoint, null, null); } catch (Exception exception) { Logger.LogError(LoggerSection.Network, $"Error sending UDP data to {ipEndPoint}: {exception}"); } }
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}"); }
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); }
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); }
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"); } }
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"); } }
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"); }
// 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}"); }
public void Interact() { if (chosen == null) { Logger.LogNotice(LoggerSection.Interactions, "Unable to interact without any chosen interactable"); return; } if (IsInteractionDisabled()) { Logger.LogNotice(LoggerSection.Interactions, "Not calling interaction, because interaction is disabled"); return; } chosen.Interact(); }
private void OnConnection(IAsyncResult result) { try { IPEndPoint clientIpEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] data = udpClient.EndReceive(result, ref clientIpEndPoint); // Start listening for the next client connection udpClient.BeginReceive(OnConnection, null); if (data.Length < sizeof(int)) { return; } Packet packet = new Packet(data); int playerId = packet.ReadInt(); if (!playersManager.clients.ContainsKey(playerId)) { Logger.LogNotice(LoggerSection.Network, $"Skipping tcp packed from player {playerId}, because it is already disconnected"); return; } if (!playersManager.clients[playerId].IsConnectedViaUdp()) { playersManager.clients[playerId].ConnectUdp(clientIpEndPoint); return; } if (!playersManager.clients[playerId].IsCorrectUdpIpEndPoint(clientIpEndPoint)) { Logger.LogError(LoggerSection.Network, "Hacking attempt, client ids doesn't match"); return; } HandlePacketData(playerId, packet); } catch (ObjectDisposedException objectDisposedException) { Logger.LogNotice(LoggerSection.Network, $"Error receiving UDP data because udpClient is already disposed: {objectDisposedException}"); } catch (Exception exception) { Logger.LogError(LoggerSection.Network, $"Error receiving UDP data: {exception}"); } }
public void SendPacket(Packet packet) { if (udpClient == null) { throw new Exception("Uninitialized UdpClient"); } try { packet.InsertInt(connectionToServer.myPlayerId); udpClient.BeginSend(packet.ToArray(), packet.GetLength(), null, null); } catch (Exception exception) { Logger.LogError(LoggerSection.Network, $"Error sending data through udp: {exception}"); } }
private string GetLabelText() { switch (textLabel.text) { case TextLabelOneDot: return(TextLabelTwoDots); case TextLabelTwoDots: return(TextLabelThreeDots); case TextLabelThreeDots: return(TextLabelOneDot); default: Logger.LogError(LoggerSection.MainMenu, "Undefined textLabel text"); return(""); } }
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"); }
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"); }
public void LateUpdate() { if (target == null) { Logger.LogNotice(LoggerSection.PlayerCamera, "Not updating, because the target is null"); return; } Vector3 desiredPosition = target.transform.position + offset; if (shaking) { Random random = new Random(); int randomX = random.Next(-50, 50); int randomY = random.Next(-50, 50); desiredPosition += new Vector3(randomX * shakeFactor, randomY * shakeFactor, 0); } Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, 1 - smoothFactor); transform.position = smoothedPosition; }
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); }
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"); }
public void ConnectToLobby() { Logger.LogEvent(LoggerSection.Connection, "Connecting to a server"); connectionToServer.Connect(); metaMonoBehaviours.applicationCallbacks.ScheduleOnApplicationQuitActions(OnApplicationQuit); }