static void UpdatePlayerStatus(UdpClient client, uint pid, PlayerStatus status) { NetWerewolfPlayer ap = ConnectedPlayers.Find(p => p.PlayerID == pid); ap.Status = status; UpdatePlayerList.Invoke(pid, status == PlayerStatus.Dead); }
private void ListenerOnPeerDisconnectedEvent(NetPeer peer, DisconnectInfo disconnectInfo) { if (!ConnectedPlayers.TryGetValue(peer.Id, out Player player)) { return; } _logger.Info($"Player {player.Username} lost connection! Reason: {disconnectInfo.Reason}"); switch (disconnectInfo.Reason) { case DisconnectReason.RemoteConnectionClose: ChatLogPanel.PrintGameMessage($"Player {player.Username} disconnected!"); break; case DisconnectReason.Timeout: ChatLogPanel.PrintGameMessage($"Player {player.Username} timed out!"); break; default: ChatLogPanel.PrintGameMessage($"Player {player.Username} lost connection!"); break; } HandlePlayerDisconnect(player); }
private async void Ready() { IsReady = true; IsPageEnabled = false; bool result; try { result = await lobbyServer.CreateLobby(CreateLobbySettings()); ClientProxyManager.Instance.RegisterLobby(this); } catch (Exception) { MessageBox.Show("Connection lost.", "Hanksite", MessageBoxButton.OK); Application.Current.Shutdown(); return; } IsPageEnabled = true; if (!result) { MessageBox.Show("The given lobby name is already used.", "Hanksite", MessageBoxButton.OK); IsReady = false; return; } ConnectedPlayers.Add(new Player() { Username = ClientProxyManager.Instance.UserName }); NotifyPropertyChanged("ConnectedPlayers"); NotifyPropertyChanged("IsLobbyFull"); }
public static void ClientDisconnectedEventHandler(UdpClient client) { NetWerewolfPlayer player = client.GetPlayer(); player.Status = PlayerStatus.Dead; ServerInstance.Send(2, player.PlayerID); // RemoteClientDisconnected(uint) ServerInstance.Send(5, 0u, $"{player.Name} has fallen..."); try { ConnectedPlayers.Remove(player); GameInfo.Players.Remove(player); } catch { } try { NetWerewolfPlayer nextHost = ConnectedPlayers.First(); if (nextHost != null && !nextHost.IsHost) { nextHost.IsHost = true; nextHost.PlayerClient.Send(199, true); ServerInstance.Send(5, 0, $"{nextHost.Name} is now the game master."); } } catch { } // No players left to be host }
public LobbyManager(ClientMessaging clientMessaging, ConnectedPlayers connectedPlayers) { _clientMessaging = clientMessaging; _clientMessaging.RegisterMessaging((short)NetworkMessages.OpenScene, OpenScene); _clientMessaging.RegisterMessaging((short)NetworkMessages.StartGame, StartGameClient); SetupPlayers(connectedPlayers); }
//This function will manage all the movement and coordination across players (notifies other players if someone has moved, to reflect that and stuff) private void updateMovements() { //First find the player who made the movement (Querying through all your players is not the most efficient way, I'll fix this later when i get a good base, remind me ok?) Character changedplayer = ConnectedPlayers.Where(f => f.Connection.RemoteUniqueIdentifier == inc.SenderConnection.RemoteUniqueIdentifier).FirstOrDefault(); //This is interesting for you to look at. I currently only send the updated movement to all players in the same zone HOWEVER //If you only want to update players in a specific range you can perform some square root math function to get the distance between each player and //add an if statement to only send it to players who are in x range. so.. (if (range > 20) -> abort) I can help with that later if you want, remind me. changedplayer.Coordinates = new Vector3(inc.ReadFloat(), inc.ReadFloat()); foreach (Character ch in ConnectedPlayers.Where(f => f.CurrentZone == changedplayer.CurrentZone)) { //Don't send the coordinates to yourself, that would be silly unless you want your own movement to be server sided as well if (ch.Connection.RemoteUniqueIdentifier == inc.SenderConnection.RemoteUniqueIdentifier) { continue; } NetOutgoingMessage outmsg = Server.CreateMessage(); outmsg.Write((byte)PacketTypes.MOVEMENTUPDATE); //Send player so players know whos' coordinates to update. You can just send the entire class but that's just so unnecessary.. outmsg.Write(changedplayer.Name); //Normally you want to give each player a unique ID (int), lighter to transport and other various reasons. Remind me outmsg.Write(changedplayer.Coordinates.X); outmsg.Write(changedplayer.Coordinates.Y); Server.SendMessage(outmsg, ch.Connection, NetDeliveryMethod.ReliableOrdered, 0); break; } }
private void OnUserConnected(string nick) { ConnectedPlayers.Add(new ListItem { Nick = nick }); AvailablePlayers.Add(nick); }
public void AddPlayerToConnectedPlayers(string _playerID, GameObject _playerObject) { if (!ConnectedPlayers.ContainsKey(_playerID)) { ConnectedPlayers.Add(_playerID, _playerObject); NumConnectedPlayers++; } }
public void RemovePlayerFromConnectedPlayers(string _playerID) { if (ConnectedPlayers.ContainsKey(_playerID)) { ConnectedPlayers.Remove(_playerID); NumConnectedPlayers--; } }
public GameObject GetPlayerFromConnectedPlayers(string _playerID) { if (ConnectedPlayers.ContainsKey(_playerID)) { return(ConnectedPlayers[_playerID]); } return(null); }
private void OnPlayerFinished(string nick) { if (ConnectedPlayers.Select(item => item.Nick).Contains(nick)) { ConnectedPlayers.First(item => item.Nick == nick).IsPlaying = false; } AvailablePlayers.Add(nick); }
private void ListenerOnNetworkLatencyUpdateEvent(NetPeer peer, int latency) { if (!ConnectedPlayers.TryGetValue(peer.Id, out Player player)) { return; } player.Latency = latency; }
private void SetupPlayers(ConnectedPlayers connectedPlayers) { _loadingWindows = InterfaceHelper.FindObjects <ILoadingWindow>().ToList(); _connectedPlayers = connectedPlayers; _connectedPlayers.OnPlayerConnected += CheckReady; _connectedPlayers.OnPlayerDisconnected += CheckReady; _connectedPlayers.OnPlayerUpdated += CheckReady; }
/// <summary> /// Get the Player object by username. Warning, expensive call!!! /// </summary> public Player GetPlayerByUsername(string username) { if (username == HostPlayer.Username) { return(HostPlayer); } else { return(ConnectedPlayers.Single(z => z.Value.Username == username).Value); } }
public bool Register(string nick) { if (ConnectedPlayers.ContainsKey(nick)) { return(false); } ConnectedPlayers.Add(nick, new PlayingClient(ClientCallback)); return(true); }
private IEnumerator Start() { networkManager = GameObject.Find("NetworkManager"); connectedPlayers = networkManager.GetComponent <ConnectedPlayers>(); m_StartWait = new WaitForSeconds(m_StartDelay); m_EndWait = new WaitForSeconds(m_EndDelay); //yield return StartCoroutine(WaitForPlayers(2)); return(null); }
/// <summary> /// Disconnects all players from the server /// </summary> public void DisconnectAll() { Log.Info("Disconnecting all users"); foreach (var player in ConnectedPlayers.Keys) { player.Disconnect(); ConnectedPlayers[player].Abort(); //Kill the thread } ConnectedPlayers.Clear(); }
public override void OnStartServer() { base.OnStartServer(); _serverMessaging = new ServerMessaging(this); Players = new ServerConnectedPlayers(_serverMessaging, this, _userName); OnServerStarted?.Invoke(); Debug.Log("Server Started"); }
private static void Postfix(ref ZNet __instance, ref ZRpc rpc) { ZNetPeer peer = __instance.GetPeer(rpc); if (peer.m_characterID.IsNone() || !ZNet.instance.IsServer() || !__instance.IsConnected(peer.m_uid) || ConnectedPlayers.Contains(peer.m_characterID.userID)) { return; } ConnectedPlayers.Add(peer.m_characterID.userID); ValheimEventHandler.OnPlayerJoined(GetPlayerInfoFromPeer(peer)); }
static void VerifyRoleHashesAndSendClientList(UdpClient sender, string playerName, string[] roleHashes) { // TODO: verify the role hashes if (roleHashes.Length < LoadedRoleHashes.Count) { NetBase.WriteDebug($"Received role hash list from {sender.EndPoint as IPEndPoint} \"{playerName}\" has less roles than the server, impossible to verify roles."); ConnectedPlayers.Remove(sender.GetPlayer()); sender.Disconnect(); return; } for (int i = 0; i < LoadedRoleHashes.Count; ++i) { string hash = LoadedRoleHashes[i]; if (!roleHashes.Contains(hash)) { NetBase.WriteDebug($"Client {sender.EndPoint as IPEndPoint} \"{playerName}\" missing hash {hash} corresponding to role {LoadedRoleTypes.Values.ElementAt(i).AssemblyQualifiedName}!"); ConnectedPlayers.Remove(sender.GetPlayer()); sender.Disconnect(); return; } else { NetBase.WriteDebug($"{sender.EndPoint as IPEndPoint}: {hash} {LoadedRoleTypes.Values.ElementAt(i).AssemblyQualifiedName} success!"); } } NetWerewolfPlayer playerRef = sender.GetPlayer(); playerRef.Name = playerName; playerRef.RoleListVerified = true; GameInfo.AddPlayerAndAssignId(playerRef); ServerInstance.Send(5, 0u, GenRandomJoinMessage(playerName)); if (GameInfo.Players.Count == 1) { playerRef.IsHost = true; sender.Send(199, true); //SetHost(UdpClient, bool) ServerInstance.Send(5, 0u, $"{playerRef.Name} is now the game master."); } sender.Send(200, playerRef.PlayerID, ConnectedPlayers.Select(p => p.PlayerID).ToArray(), ConnectedPlayers.Select(p => p.Name).ToArray()); // ReceivePlayerList(uint, uint[], string[]); foreach (string hash in ActiveRoleHashes) { sender.Send(190, hash, false); } ServerInstance.Send(1, playerRef.PlayerID, playerRef.Name); // UpdateClientInfo(uint, string) }
/// <summary> /// Adds a connected player to the server /// </summary> /// <param name="connection">Connected player using a .NET Socket</param> public void AddConnection(Socket connection) { var player = (IPlayer)ScriptFactory.GetScript(MudDesigner.Engine.Properties.EngineSettings.Default.PlayerScript, null); player.Initialize(InitialConnectionState, connection, this); Thread userThread = new Thread(ReceiveDataThread); ConnectedPlayers.Add(player, userThread); userThread.Start(player); }
private static void Prefix(ref ZNet __instance, ref ZRpc rpc) { ZNetPeer peer = __instance.GetPeer(rpc); if (peer.m_characterID.IsNone() || !ZNet.instance.IsServer() || !__instance.IsConnected(peer.m_uid)) { return; } ConnectedPlayers.Remove(peer.m_uid); ValheimEventHandler.OnPlayerDisconnected(GetPlayerInfoFromPeer(peer)); }
private void Cancel() { IsReady = false; try { lobbyServer.DisconnectFromLobby(); ClientProxyManager.Instance.RemoveLobby(); } catch (Exception) { MessageBox.Show("Connection lost.", "Hanksite", MessageBoxButton.OK); Application.Current.Shutdown(); return; } ConnectedPlayers.Clear(); }
/// <summary> /// Disconnects all players from the server /// </summary> private void DisconnectPlayer(IPlayer connectedUser) { try { Thread playerThread = ConnectedPlayers[connectedUser]; ConnectedPlayers.Remove(connectedUser); connectedUser.Disconnect(); connectedUser = null; playerThread.Abort(); } catch (Exception ex) { Log.Error(string.Format("Error when disconnecting players. {0}", ex.Message)); } }
static void RemoteClientDisconnected(UdpClient client, uint pid) { if (LocalPlayer.PlayerID == pid) { CloseClientInstance(); } if (ServerInstance == null) { ConnectedPlayers.Remove(ConnectedPlayers.Find(p => p.PlayerID == pid)); } // TODO: GameInfo removal (Maybe make dead if alive, and then remove once spectator?) UpdatePlayerList.Invoke(pid, true); }
public void OnOpen(IWebSocketConnection socket) { Logger.Log(this, "A connection was opened. (Socket ID: {0})", socket.ConnectionInfo.Id); // Respond to a join request by assigning a unique ID to the connection and sending it back to the client var player = AddPlayer(socket); player.RequestClientInfo(); // Wait for player reponse with their name player.Socket.OnBinary += (binary) => { // Messages are sent as binary from Unity (the WebGL wrapper only sends binary for some reason) var message = Encoding.UTF8.GetString(binary); Message.IsType <ClientMessage.GiveClientInfo>(message, (data) => { if (data.ProtocolVersion != ProtocolInfo.Version) { // Notify protocol mismatch. Client and Server must match! player.SendConnectionError(ConnectionError.ProtocolMismatch); return; } // Check if name is within character range bool nameWithinCharLimit = data.Name.Length >= SettingsLoader.Values.Server.NameMinChars && data.Name.Length <= SettingsLoader.Values.Server.NameMaxChars; // Check if an existing connection already has that name bool nameisUnique = !ConnectedPlayers.Any(x => x.Data.Name.ToLower() == data.Name.ToLower()); if (nameWithinCharLimit && nameisUnique) { OnConnectionSuccessful(player, data); } else if (!nameWithinCharLimit) { player.SendConnectionError(ConnectionError.InvalidNameLength); } else { player.SendConnectionError(ConnectionError.MatchesExistingName); } }); }; }
public bool GetRandomAvailablePlayer(string nick, out string otherNick) { var list = ConnectedPlayers.Where(pair => pair.Key != nick && pair.Value.IsPlaying == false).Select(pair => pair.Key).ToList(); if (list.Count < 1) { otherNick = ""; return(false); } otherNick = list[_availablePlayerRandom.Next(list.Count)]; while (otherNick == nick) { otherNick = list[_availablePlayerRandom.Next(list.Count)]; } return(true); }
static void UpdateClientInfo(UdpClient client, uint pid, string name) { NetWerewolfPlayer player = ConnectedPlayers.FirstOrDefault(p => p.PlayerID == pid); if ((player == null) || (player.PlayerID != LocalPlayer.PlayerID)) { player = new NetWerewolfPlayer(pid, name); if (ServerInstance == null) { ConnectedPlayers.Add(player); } UpdatePlayerList.Invoke(player.PlayerID, false); } else { player.Name = name; } }
/// <summary> /// When we get a message from a client, we handle the message here /// and perform any necessary tasks. /// </summary> private void ListenerOnNetworkReceiveEvent(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod) { try { // Handle ConnectionRequest as special case if (reader.PeekByte() == 0) { Command.Parse(reader, out CommandHandler handler, out byte[] message); ConnectionRequestHandler requestHandler = (ConnectionRequestHandler)handler; requestHandler.HandleOnServer(message, peer); return; } // Parse this message ConnectedPlayers.TryGetValue(peer.Id, out Player player); bool relayOnServer = Command.ParseOnServer(reader, player); if (relayOnServer) { // Copy relevant message part (exclude protocol headers) byte[] data = new byte[reader.UserDataSize]; Array.Copy(reader.RawData, reader.UserDataOffset, data, 0, reader.UserDataSize); // Send this message to all other clients var peers = _netServer.ConnectedPeerList; foreach (var client in peers) { // Don't send the message back to the client that sent it. if (client.Id == peer.Id) { continue; } // Send the message so the other client can stay in sync client.Send(data, DeliveryMethod.ReliableOrdered); } } } catch (Exception ex) { ChatLogPanel.PrintGameMessage(ChatLogPanel.MessageType.Error, "Error while parsing command. See log."); _logger.Error(ex, $"Encountered an error while reading command from {peer.EndPoint.Address}:{peer.EndPoint.Port}:"); } }
private void Start() { if (isServer) { DeathRaceManager.AddCar(this); NetworkServer.RegisterHandler(MessageToServer, ServerRecieveMessage); } if (isLocalPlayer) { CmdSetNameAndType(Prototype.NetworkLobby.LobbyManager.loggedInName, Prototype.NetworkLobby.LobbyManager.carType); if (carType == 0) { GetComponent <CarHealth>().CmdSetStartHealth(50); GetComponent <CarHealth>().CmdUpdateSliderMax(50); } else if (carType == 2) { GetComponent <CarHealth>().CmdSetStartHealth(500); GetComponent <CarHealth>().CmdUpdateSliderMax(50); } else { GetComponent <CarHealth>().CmdSetStartHealth(100); GetComponent <CarHealth>().CmdUpdateSliderMax(100); } } connectedPlayers = GetComponent <ConnectedPlayers>(); m_MovementAxisName = "Vertical" + 1; m_TurnAxisName = "Horizontal" + 1; m_resetButton = "Reset" + 1; m_90sButton = "90s" + 1; m_LapsText.text = m_laps.ToString() + "/" + m_TotalLaps; m_resetLocation.transform.parent = null; m_EngineAudio.clip = m_EngineIdle; m_EngineAudio.loop = true; m_EngineAudio.volume = 0.1f; m_BackTurbineSource.clip = m_BackTurbine; m_RunningInThe90sAudio.clip = m_RunningInThe90s; m_CatOnImage.sprite = m_Empty; }