private void OnJoin(JoinPacket packet, NetPeer peer) { Debug.Log("[S] Join packet received: " + packet.UserName); var serverCharacter = new ServerCharacter(packet.UserName, peer, Gameconfig.StartingPoint[peer.Id]); _serverManager.AddCharadcter((byte)peer.Id, serverCharacter); //Send join accept var ja = new JoinAcceptPacket { Id = (byte)peer.Id, UserName = packet.UserName, ServerTick = _serverTick }; peer.Send(WritePacket(ja), SendType.ReliableOrdered); // 들어온 친구한테 기존 정보 다 보내줌 var pj = new CharacterJoinedPacket { UserName = packet.UserName, NewCharacter = true, CharacterPacket = serverCharacter.CharacterPacket, ServerTick = _serverTick }; _netManager.SendToAll(WritePacket(pj), SendType.ReliableOrdered, peer); // 이전 유저들에게 정보 다 보내줌 pj.NewCharacter = false; foreach (var pair in _serverManager.Characters.Where(pair => pair.Key != (byte)peer.Id)) { pj.UserName = pair.Value._data.Name; pj.CharacterPacket = pair.Value.CharacterPacket; peer.Send(WritePacket(pj), SendType.ReliableOrdered); } }
public void OnJoin(IWorldClient client, JoinPacket packet) { DbCharacter character = _database.Characters.Include(x => x.User).FirstOrDefault(x => x.Id == packet.PlayerId); if (character == null) { _logger.LogError($"Invalid player id received from client; cannot find player with id: {packet.PlayerId}"); return; } if (character.IsDeleted) { _logger.LogWarning($"Cannot connect with character '{character.Name}' for user '{character.User.Username}'. Reason: character is deleted."); return; } if (character.User.Authority <= 0) { _logger.LogWarning($"Cannot connect with '{character.Name}'. Reason: User {character.User.Username} is banned."); // TODO: send error to client return; } client.Player = _playerFactory.CreatePlayer(character); client.Player.Connection = client; _worldSpawnPacketFactory.SendPlayerSpawn(client.Player); client.Player.Object.Spawned = true; client.Player.PlayerData.LoggedInAt = DateTime.UtcNow; }
public static void Handle(JoinPacket packet, NetPeer peer) { Console.WriteLine($"Received join from {packet.username} (pid: {(uint)peer.Id})"); ServerPlayer newPlayer = (Server.players[(uint)peer.Id] = new ServerPlayer { peer = peer, state = new PlayerState { pid = (uint)peer.Id, username = packet.username, position = packet.position, level = packet.level, animationState = 0, }, username = packet.username, }); // Send server player state back to client Server.SendPacket(new JoinAcceptPacket { state = newPlayer.state }, peer, DeliveryMethod.ReliableOrdered); // for each player currently in the server, send each player info to the client to render a remoteplayer character foreach (ServerPlayer player in Server.players.Values) { if (player.state.pid != newPlayer.state.pid) { Server.SendPacket(new PlayerJoinedGamePacket { player = new ClientPlayer { username = newPlayer.username, state = newPlayer.state, }, }, player.peer, DeliveryMethod.ReliableOrdered); Server.SendPacket(new PlayerJoinedGamePacket { player = new ClientPlayer { username = player.username, state = player.state, }, }, newPlayer.peer, DeliveryMethod.ReliableOrdered); } } }
private void OnJoinReceived(JoinPacket joinPacket, NetPeer peer) { Debug.Log("[S] Join packet received: " + joinPacket.UserName); var player = new ServerPlayer(_playerManager, joinPacket.UserName, peer); _playerManager.AddPlayer(player); player.Spawn(new Vector2(Random.Range(-2f, 2f), Random.Range(-2f, 2f))); //Send join accept var ja = new JoinAcceptPacket { Id = player.Id, ServerTick = _serverTick }; peer.Send(WritePacket(ja), DeliveryMethod.ReliableOrdered); //Send to old players info about new player var pj = new PlayerJoinedPacket { UserName = joinPacket.UserName, NewPlayer = true, InitialPlayerState = player.NetworkState, ServerTick = _serverTick }; _netManager.SendToAll(WritePacket(pj), DeliveryMethod.ReliableOrdered, peer); //Send to new player info about old players pj.NewPlayer = false; foreach (ServerPlayer otherPlayer in _playerManager) { if (otherPlayer == player) { continue; } pj.UserName = otherPlayer.Name; pj.InitialPlayerState = otherPlayer.NetworkState; peer.Send(WritePacket(pj), DeliveryMethod.ReliableOrdered); } }
public static void OnJoin(WorldClient client, INetPacketStream packet) { var joinPacket = new JoinPacket(packet); DbCharacter character = null; using (var database = DependencyContainer.Instance.Resolve <IDatabase>()) character = database.Characters.Get(joinPacket.PlayerId); if (character == null) { Logger.Error($"Invalid player id received from client; cannot find player with id: {joinPacket.PlayerId}"); return; } if (character.IsDeleted) { Logger.Warn($"Cannot connect with character '{character.Name}' for user '{character.User.Username}'. Reason: character is deleted."); return; } if (character.User.Authority <= 0) { Logger.Info($"User {character.User.Username} is banned."); // TODO: send error to client return; } IMapInstance map = DependencyContainer.Instance.Resolve <MapLoader>().GetMapById(character.MapId); if (map == null) { Logger.Warn("Map with id '{0}' doesn't exist.", character.MapId); // TODO: send error to client or go to default map ? return; } IMapLayer mapLayer = map.GetMapLayer(character.MapLayerId) ?? map.GetDefaultMapLayer(); // 1st: Create the player entity with the map context client.Player = map.CreateEntity <PlayerEntity>(); // 2nd: create and initialize the components client.Player.Object = new ObjectComponent { ModelId = character.Gender == 0 ? 11 : 12, Type = WorldObjectType.Mover, MapId = character.MapId, LayerId = mapLayer.Id, Position = new Vector3(character.PosX, character.PosY, character.PosZ), Angle = character.Angle, Size = 100, Name = character.Name, Spawned = false, Level = character.Level }; client.Player.Health = new HealthComponent { Hp = character.Hp, Mp = character.Mp, Fp = character.Fp }; client.Player.VisualAppearance = new VisualAppearenceComponent { Gender = character.Gender, SkinSetId = character.SkinSetId, HairId = character.HairId, HairColor = character.HairColor, FaceId = character.FaceId, }; client.Player.PlayerData = new PlayerDataComponent { Id = character.Id, Slot = character.Slot, Gold = character.Gold, Authority = (AuthorityType)character.User.Authority, Experience = character.Experience, JobId = character.ClassId }; client.Player.MovableComponent = new MovableComponent { Speed = GameResources.Instance.Movers[client.Player.Object.ModelId].Speed, DestinationPosition = client.Player.Object.Position.Clone(), LastMoveTime = Time.GetElapsedTime(), NextMoveTime = Time.GetElapsedTime() + 10 }; client.Player.Statistics = new StatisticsComponent(character); var behaviors = DependencyContainer.Instance.Resolve <BehaviorLoader>(); client.Player.Behavior = behaviors.PlayerBehaviors.DefaultBehavior; client.Player.Connection = client; // Initialize the inventory var inventoryEventArgs = new InventoryInitializeEventArgs(character.Items); client.Player.NotifySystem <InventorySystem>(inventoryEventArgs); // Taskbar foreach (var applet in character.TaskbarShortcuts.Where(x => x.TargetTaskbar == ShortcutTaskbarTarget.Applet)) { if (applet.Type == ShortcutType.Item) { var item = client.Player.Inventory.GetItem(x => x.Slot == applet.ObjectId); client.Player.Taskbar.Applets.CreateShortcut(new Shortcut(applet.SlotIndex, applet.Type, (uint)item.UniqueId, applet.ObjectType, applet.ObjectIndex, applet.UserId, applet.ObjectData, applet.Text)); } else { client.Player.Taskbar.Applets.CreateShortcut(new Shortcut(applet.SlotIndex, applet.Type, applet.ObjectId, applet.ObjectType, applet.ObjectIndex, applet.UserId, applet.ObjectData, applet.Text)); } } foreach (var item in character.TaskbarShortcuts.Where(x => x.TargetTaskbar == ShortcutTaskbarTarget.Item)) { if (item.Type == ShortcutType.Item) { var inventoryItem = client.Player.Inventory.GetItem(x => x.Slot == item.ObjectId); client.Player.Taskbar.Items.CreateShortcut(new Shortcut(item.SlotIndex, item.Type, (uint)inventoryItem.UniqueId, item.ObjectType, item.ObjectIndex, item.UserId, item.ObjectData, item.Text), item.SlotLevelIndex.HasValue ? item.SlotLevelIndex.Value : -1); } else { client.Player.Taskbar.Items.CreateShortcut(new Shortcut(item.SlotIndex, item.Type, item.ObjectId, item.ObjectType, item.ObjectIndex, item.UserId, item.ObjectData, item.Text), item.SlotLevelIndex.HasValue ? item.SlotLevelIndex.Value : -1); } } TestCommand.OnTest(client.Player, new string[] { }); var list = new List <Shortcut>(); foreach (var skill in character.TaskbarShortcuts.Where(x => x.TargetTaskbar == ShortcutTaskbarTarget.Queue)) { list.Add(new Shortcut(skill.SlotIndex, skill.Type, skill.ObjectId, skill.ObjectType, skill.ObjectIndex, skill.UserId, skill.ObjectData, skill.Text)); } client.Player.Taskbar.Queue.CreateShortcuts(list); // 3rd: spawn the player WorldPacketFactory.SendPlayerSpawn(client.Player); // 4th: player is now spawned client.Player.Object.Spawned = true; client.LoggedInAt = DateTime.UtcNow; }
protected override void OnMessage(MessageEventArgs e) { // Console.WriteLine(e.Data); Packet packet = JsonConvert.DeserializeObject <Packet>(e.Data); string socketID = ID; // join packet -- 0 if (packet.type == Packets.JOIN) { JoinPacket jPacket = JsonConvert.DeserializeObject <JoinPacket>(packet.data); joinLobby(jPacket.lobbyID, jPacket.playerID, jPacket.name, socketID); } // create packet -- 1 else if (packet.type == Packets.CREATE) { try { Console.WriteLine("making new create packet"); // Create a lobby with given parameters CreatePacket createPacket = JsonConvert.DeserializeObject <CreatePacket>(packet.data); createLobby(createPacket.maxPlayers, createPacket.name, createPacket.playerID, socketID, Context.WebSocket); } catch (NullReferenceException nre) { Console.WriteLine("hi"); Console.WriteLine(nre); } } // start packet -- 2 else if (packet.type == 2) { startGame(packet); } else if (packet.type == Packets.PLAYER_INPUT) { PlayerInputPacket playerInputPacket = JsonConvert.DeserializeObject <PlayerInputPacket>(packet.data); Player currentPlayer = null; foreach (Player player in lobbies[playerInputPacket.lobbyID].players) { if (player.socketID == ID) { currentPlayer = player; } } if (currentPlayer == null) { // no valid player found in lobby return; } // validate move foreach (Player player in lobbies[playerInputPacket.lobbyID].players) { if (player.socketID != ID) { if (player.currentBlockPosition != null) { foreach (int[] pos1 in player.currentBlockPosition) { foreach (int[] pos2 in playerInputPacket.shapeIndices) { if (pos1 == pos2) { Send("COLLISION"); return; } } } } } } UpdatePacket update = processInput(playerInputPacket); if (playerInputPacket.move != "freeze") { currentPlayer.currentBlockPosition = playerInputPacket.shapeIndices; playerInputPacket.playerID = currentPlayer.id; foreach (Player player in lobbies[playerInputPacket.lobbyID].players) { if (player.socketID != ID) { Sessions.SendTo(JsonConvert.SerializeObject(update), player.socketID); } } } else { // remove column is ID # 2 // remove area is ID # 3 // area removes 2 up, 2 left, 2 right, 2 down Lobby lobby = lobbies[playerInputPacket.lobbyID]; update.shapeIndices = playerInputPacket.shapeIndices; foreach (int[] pos in playerInputPacket.shapeIndices) { // FREEZE lobby.game.board.board[pos[0], pos[1]] = pos[2]; } // Prints prints = new Prints(); // Console.WriteLine("LOBBY BOARD"); // prints.PrintMultiDimArr(lobby.game.board.board); checkRows(lobby); foreach (Player player in lobby.players) { if (player.socketID != ID) { Sessions.SendTo(JsonConvert.SerializeObject(update), player.socketID); } } } // on place piece put on board ;GJ } else if (packet.type == Packets.BOT_UPDATE) // 7 { BotPacket bot = JsonConvert.DeserializeObject <BotPacket>(packet.data); if (bot.action == 1) { lobbies[bot.lobbyID].botCount++; lobbies[bot.lobbyID].numPlayers++; alertLobby(-2, bot.lobbyID, Packets.ADD_BOT); } else if (bot.action == 0) { lobbies[bot.lobbyID].botCount--; lobbies[bot.lobbyID].numPlayers--; alertLobby(-2, bot.lobbyID, Packets.REMOVE_BOT); } } else if (packet.type == Packets.SHAPE_BLUEPRINT) { ShapeBlueprintPacket sbp = JsonConvert.DeserializeObject <ShapeBlueprintPacket>(packet.data); foreach (Player player in lobbies[sbp.lobbyID].players) { if (player.socketID != ID) { Sessions.SendTo(JsonConvert.SerializeObject(sbp), player.socketID); } else { //player.currentBlock = sbp.shapeBlueprint; } } } else if (packet.type == Packets.TEAM_NAME) { // format the packet to be a scors packet with all the team information TeamPacket tPacket = JsonConvert.DeserializeObject <TeamPacket>(packet.data); foreach (Player player in lobbies[tPacket.lobbyid].players) { if (player.socketID != ID) { Sessions.SendTo(JsonConvert.SerializeObject(tPacket), player.socketID); } else { //player.currentBlock = sbp.shapeBlueprint; } } } else if (packet.type == Packets.GAME_END) { EndPacket end = JsonConvert.DeserializeObject <EndPacket>(packet.data); if (checkGameEnd(end)) { foreach (Player player in lobbies[end.lobbyID].players) { Sessions.SendTo(JsonConvert.SerializeObject(end), player.socketID); } } } else if (packet.type == Packets.POS_UPDATE) { PositionPacket pp = JsonConvert.DeserializeObject <PositionPacket>(packet.data); foreach (Player player in lobbies[pp.lobbyID].players) { if (player.socketID == ID) { player.currentBlockPosition = pp.shapeIndices; } } } else { Console.WriteLine("bad packet"); Console.WriteLine(packet.type); Send("bad packet!!! :("); } }
/// <summary> /// Change team method /// </summary> /// <param name="TeamId">new teamId</param> /// <returns>true if successfull</returns> public bool ChangeTeam(ushort TeamId) { bool result = true; try { if (playerIdField.HasValue && gameIdField.HasValue && teamIdField.HasValue) { GameInfoPacket gPack = (GameInfoPacket)gameInfoPackets.LastPacket; if (gPack == null) return false; List<ushort> teamIdList = new List<ushort>(); List<ushort> playerIdList = new List<ushort>(); for (int k = 0; k < gPack.TeamScoreList.Count; k++) teamIdList.Add(gPack.TeamScoreList[k].TeamId); for (int k = 0; k < gPack.PlayerStatusList.Count; k++) teamIdList.Add(gPack.PlayerStatusList[k].PlayerId); //todo: exception ? //maybe it would be better to throw exception ?? if (!teamIdList.Contains(TeamId)) return false; if (!playerIdList.Contains(playerIdField.Value)) return false; teamIdField = TeamId; JoinPacket joinPacket = new JoinPacket(); joinPacket.PlayerId = playerIdField.Value; joinPacket.TeamId = teamIdField.Value; joinPacket.TimeStamp = DateTime.Now; joinPacket.PlayerName = playerNameField; joinPacket.GameId = gameIdField.Value; joinPacket.PacketId = packetIdCounter.Next(); AddMessageToServer(joinPacket); } else result = false; } catch (Exception ex) { Diagnostic.NetworkingDiagnostics.Logging.Fatal("Change team S", ex); result = false; } return result; }
/// <summary> Method that joins Player to server /// /// </summary> /// <param name="ServerIp">server ip adress</param> /// <param name="PlayerName">name of joining player</param> /// <param name="GameId">game id</param> /// <returns>Player Id</returns> public bool JoinGame(IPEndPoint ServerIp, string PlayerName, ushort GameId, ushort TeamId) { bool result = true; try { if (lanBroadcast != null) lanBroadcast.STOP(); udpNetworking.ServerIp = ServerIp; udpNetworking.StartUdpSocket(); JoinPacket joinPacket = new JoinPacket(); joinPacket.PacketId = packetIdCounter.Next(); // id <1000 means that id hasn't been selected joinPacket.PlayerId = 0; joinPacket.PlayerName = PlayerName; joinPacket.GameId = GameId; joinPacket.TeamId = TeamId; playerNameField = PlayerName; gameIdField = GameId; teamIdField = TeamId; // now we should inform player about other palyer that are in the game he wants to join GameInfoPacket gip = null; lock (gameInfoPacketsLock) { gip = (GameInfoPacket) gameInfoPackets[GameId].LastPacket; } if (gip != null) { lock(gameEventListLock) { for (int i = 0; i < gip.PlayerStatusList.Count; i++) gameEventList.Add(new GameEvents.PlayerJoinedEvent(gip.PlayerStatusList[i].PlayerId, gip.PlayerStatusList[i].PlayerName, gip.PlayerStatusList[i].PlayerTeam)); } } udpNetworking.SendPacket(joinPacket.ToByte()); } catch (Exception ex) { result = false; Diagnostic.NetworkingDiagnostics.Logging.Fatal("Join", ex); } return result; }
static void Main(string[] args) { UDPClientServerCommons.Usefull.PlayerData pd = new UDPClientServerCommons.Usefull.PlayerData(); pd.Duck = true; bool tst = pd.Duck; byte[] binary = null; Vector vector = new Vector(34.35f, 12.89f, 31.98f); Console.WriteLine(vector); binary = vector.ToMinimalByte(); Vector newVector = new Vector(binary,0); Console.WriteLine(newVector); Console.ReadLine(); Console.WriteLine("========================================"); // ClientPacket testClientPacket = new ClientPacket(); ClientPacket testClientPacket = new ClientPacket(); //testClientPacket.PacketId = 10; testClientPacket.PlayerCarringWeponOne = true; testClientPacket.PlayerCarringWeponTwo = false; testClientPacket.PlayerDucking = true; testClientPacket.PlayerId = 67; testClientPacket.PlayerJumping = true; testClientPacket.PlayerLookingDirection = new Vector(45.56f, 34.67f, 87.45f); testClientPacket.PlayerMovementDirection = new Vector(43.54f, 87.34f, 56.21f); testClientPacket.PlayerPosition = new Vector(1f, 5f, 67.65f); //testClientPacket.PlayerRunning = true; testClientPacket.PlayerShooting = true; //testClientPacket.PlayerWalking = false; testClientPacket.TimeStamp = DateTime.Now; testClientPacket.PacketId = 10; Console.WriteLine(testClientPacket); ClientPacket tmp = new ClientPacket(testClientPacket.ToByte()); Console.WriteLine("========================================"); Console.WriteLine(tmp); Console.WriteLine("========================================"); Console.ReadLine(); GameInfoPacket gameInfoPacket = new GameInfoPacket(); gameInfoPacket.GameType = GameTypeEnumeration.Objective; gameInfoPacket.Limit = 10; gameInfoPacket.PacketId = 6889; gameInfoPacket.GameId = 10; gameInfoPacket.ServerAddress = new IPEndPoint(IPAddress.Parse("90.156.78.90"), 1234); PlayerStatus ps1 = new PlayerStatus(); ps1.PlayerHealth = 100; ps1.PlayerId = 8; ps1.PlayerName = "Karpik"; ps1.PlayerPing = 23; ps1.PlayerScore = 3; ps1.PlayerTeam = 1; PlayerStatus ps2 = new PlayerStatus(); ps2.PlayerHealth = 78; ps2.PlayerId = 2; ps2.PlayerName = "Ziomek"; ps2.PlayerPing = 34; ps2.PlayerScore = 7; ps2.PlayerTeam = 2; gameInfoPacket.PlayerStatusList.Add(ps1); gameInfoPacket.PlayerStatusList.Add(ps2); TeamData ts1 = new TeamData(); ts1.TeamId = 1; ts1.TeamScore = 89; ts1.TeamName = "the crazy killers"; TeamData ts2 = new TeamData(); ts2.TeamId = 2; ts2.TeamScore = 45; ts2.TeamName = "what the fuckers"; gameInfoPacket.TeamScoreList.Add(ts1); gameInfoPacket.TeamScoreList.Add(ts2); gameInfoPacket.TimeStamp = DateTime.Now; Console.WriteLine(gameInfoPacket); GameInfoPacket tmp2 = new GameInfoPacket(gameInfoPacket.ToByte()); Console.WriteLine("========================================"); Console.WriteLine(tmp2); Console.WriteLine("========================================"); Console.ReadLine(); JoinPacket joinPacket = new JoinPacket(); joinPacket.GameId = 1; joinPacket.PacketId = 6543; joinPacket.PlayerId = 34; joinPacket.PlayerName = "Ziomek2"; joinPacket.TimeStamp = DateTime.Now; joinPacket.TeamId = 67; Console.WriteLine(joinPacket); JoinPacket tmp3 = new JoinPacket(joinPacket.ToByte()); Console.WriteLine("========================================"); Console.WriteLine(tmp3); Console.WriteLine("========================================"); Console.ReadLine(); LeaveGamePacket leaveGamePacket = new LeaveGamePacket(); leaveGamePacket.GameId = 56; leaveGamePacket.PacketId = 876; leaveGamePacket.PlayerId = 89; leaveGamePacket.TimeStamp = DateTime.Now; Console.WriteLine(leaveGamePacket); LeaveGamePacket tmp4 = new LeaveGamePacket(leaveGamePacket.ToByte()); Console.WriteLine("========================================"); Console.WriteLine(tmp4); Console.WriteLine("========================================"); Console.ReadLine(); PlayerInfo testClientPacket2 = new PlayerInfo(); //testClientPacket.PacketId = 10; testClientPacket2.PlayerCarringWeponOne = false; testClientPacket2.PlayerCarringWeponTwo = true; testClientPacket2.PlayerDucking = true; testClientPacket2.PlayerId = 647; testClientPacket2.PlayerJumping = true; testClientPacket2.PlayerLookingDirection = new Vector(45.4f, 334.617f, 187.425f); testClientPacket2.PlayerMovementDirection = new Vector(473.547f, 837.343f, 546.231f); testClientPacket2.PlayerPosition = new Vector(17f, 57f, 677.675f); //testClientPacket2.PlayerRunning = true; testClientPacket2.PlayerShooting = true; //testClientPacket2.PlayerWalking = false; testClientPacket2.Health = 100; testClientPacket2.AckIds.Add(412); testClientPacket2.AckIds.Add(456); testClientPacket2.Timestamp = DateTime.Now; Console.WriteLine(testClientPacket2); PlayerInfo tmp5 = new PlayerInfo(testClientPacket2.ToByte()); Console.WriteLine("========================================"); Console.WriteLine(tmp5); Console.WriteLine("========================================"); Console.ReadLine(); ServerPacket server = new ServerPacket(); //server.NumberOfPlayers = 2; server.PacketId = 346; server.PlayerInfoList.Add(testClientPacket2); server.PlayerInfoList.Add(testClientPacket2); server.TimeStamp = DateTime.Now; Console.WriteLine(server); ServerPacket tmp6 = new ServerPacket(server.ToByte()); Console.WriteLine("========================================"); Console.WriteLine(tmp6); Console.WriteLine("========================================"); Console.ReadLine(); }