void PlayerConnect(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage()) { using (DarkRiftReader reader = message.GetReader()) { ushort ID = reader.ReadUInt16(); string playerName = reader.ReadString(); Vector3 position = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); Color32 color = new Color32(reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), 255); // Player / Network Player Spawn GameObject obj; if (ID == drClient.ID) { // If this ID corresponds to this client, spawn the controllable player prefab obj = Instantiate(localPlayerPrefab, position, Quaternion.identity) as GameObject; } else { // Else we spawn a network prefab, non-controllable obj = Instantiate(networkPlayerPrefab, position, Quaternion.identity) as GameObject; } // Set the color Renderer renderer = obj.GetComponent <MeshRenderer>(); renderer.material.color = color; // Get network entity data of prefab and add to network players store networkPlayers.Add(ID, obj.GetComponent <NetworkEntity>()); // Update player name networkPlayers[ID].SetPlayerName(playerName); } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { var client = e.Client; switch (message.Tag) { case LoginUser: using (var reader = message.GetReader()) { var username = reader.ReadString(); var password = reader.ReadString(); User user = null; using (var context = new AuthenticationContext()) { user = context .Users .FirstOrDefault( u => u.Username == username && u.Password == password ); } using (var msg = Message.CreateEmpty(user != null ? LoginSuccess : LoginFailed)) { client.SendMessage(msg, SendMode.Reliable); } } break; } } }
public void DamageHurtableRecieved(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { if (message.Tag == Tags.DamageHurtableTag) { using (DarkRiftReader reader = message.GetReader()) { while (reader.Position < reader.Length) { WorldData World = worldManager.clients[e.Client].World; DamageHurtableClientDTO data = reader.ReadSerializable <DamageHurtableClientDTO>(); using (DarkRiftWriter damageHurtableWriter = DarkRiftWriter.Create()) { DamageHurtableServerDTO damageHurtableData = new DamageHurtableServerDTO(); damageHurtableData.InstagatorID = e.Client.ID; damageHurtableData.VictimID = data.VictimID; damageHurtableData.damage = data.damage; Console.WriteLine($"{damageHurtableData.InstagatorID} damaging {damageHurtableData.VictimID} for {damageHurtableData.damage} hp"); damageHurtableWriter.Write(damageHurtableData); using (Message damageHurtableMessage = Message.Create(Tags.DamageHurtableTag, damageHurtableWriter)) { foreach (IClient client in World.GetClients()) { client.SendMessage(damageHurtableMessage, SendMode.Reliable); } } } } } } } }
// Server Responses private static void OnDataHandler(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Tags.TagsPerPlugin * Tags.Chat || message.Tag >= Tags.TagsPerPlugin * (Tags.Chat + 1)) { return; } // Private message received switch (message.Tag) { // Private message received case ChatTags.PrivateMessage: { using (var reader = message.GetReader()) { var senderName = reader.ReadString(); var content = reader.ReadString(); var chatMessage = new ChatMessage(senderName, content, MessageType.Private, senderName); Messages.Add(chatMessage); onPrivateMessage?.Invoke(chatMessage); } break; } // Private message sent case ChatTags.SuccessfulPrivateMessage: { using (var reader = message.GetReader()) { var senderName = reader.ReadString(); var receiver = reader.ReadString(); var content = reader.ReadString(); var chatMessage = new ChatMessage(senderName, content, MessageType.Private, receiver, true); Messages.Add(chatMessage); onPrivateMessage?.Invoke(chatMessage); } break; } // Room message received case ChatTags.RoomMessage: { using (var reader = message.GetReader()) { var senderName = reader.ReadString(); var content = reader.ReadString(); var chatMessage = new ChatMessage(senderName, content, MessageType.Room, "Room"); Messages.Add(chatMessage); onRoomMessage?.Invoke(chatMessage); } break; } // Group message received case ChatTags.GroupMessage: { using (var reader = message.GetReader()) { var groupName = reader.ReadString(); var senderName = reader.ReadString(); var content = reader.ReadString(); var chatMessage = new ChatMessage(senderName, content, MessageType.ChatGroup, groupName); Messages.Add(chatMessage); onGroupMessage?.Invoke(chatMessage); } break; } case ChatTags.MessageFailed: { var content = "Failed to send message."; using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid Message Failed Error data received."); } else { switch (reader.ReadByte()) { case 0: Debug.Log("Invalid Message data sent!"); break; case 1: Debug.Log("You're not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("You're not part of this chatgroup."); content = "Not connected to this chat channel. Try leaving and rejoining!"; break; case 3: Debug.Log("Failed to send message. Player is offline."); content = "Player is offline."; break; default: Debug.Log("Invalid errorId!"); break; } } } ServerMessage(content, MessageType.Error); break; } case ChatTags.JoinGroup: { using (var reader = message.GetReader()) { var group = reader.ReadSerializable <ChatGroup>(); ServerMessage("You joined the channel: " + group.Name, MessageType.ChatGroup); if (!SavedChatGroups.Contains(group.Name)) { SavedChatGroups.Add(group.Name); ArrayPrefs.SetStringArray("ChatGroups", SavedChatGroups.ToArray()); } onSuccessfulJoinGroup?.Invoke(group.Name); } break; } case ChatTags.JoinGroupFailed: { var content = "Failed to join chat group."; using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid Join Group Failed Error data received."); } else { switch (reader.ReadByte()) { case 0: Debug.Log("Invalid Join Group data sent!"); break; case 1: Debug.Log("You're not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("Alreay in this chatgroup."); content = "You are already in this chat group."; break; default: Debug.Log("Invalid errorId!"); break; } } ServerMessage(content, MessageType.Error); } break; } case ChatTags.LeaveGroup: { using (var reader = message.GetReader()) { var groupName = reader.ReadString(); ServerMessage("You left the channel: " + groupName, MessageType.ChatGroup); if (SavedChatGroups.Remove(groupName)) { ArrayPrefs.SetStringArray("ChatGroups", SavedChatGroups.ToArray()); } onSuccessfulLeaveGroup?.Invoke(groupName); } break; } case ChatTags.LeaveGroupFailed: { var content = "Failed to leave chat group."; using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid Leave Group Failed Error data received."); } else { switch (reader.ReadByte()) { case 0: Debug.Log("Invalid Leave Group data sent!"); break; case 1: Debug.Log("You're not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("No such chatgroup chatgroup."); content = "There is no chat group with this name."; break; default: Debug.Log("Invalid errorId!"); break; } } } ServerMessage(content, MessageType.Error); break; } case ChatTags.GetActiveGroups: { using (var reader = message.GetReader()) { var groupList = reader.ReadStrings().ToList(); groupList.Sort(string.CompareOrdinal); foreach (var group in groupList) { ServerMessage(group, MessageType.All); } } break; } case ChatTags.GetActiveGroupsFailed: { var content = "Failed to get list of chat groups."; using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid Get Active Groups Failed Error data received."); } else { switch (reader.ReadByte()) { case 1: Debug.Log("You're not logged in!"); SceneManager.LoadScene("Login"); break; default: Debug.Log("Invalid errorId!"); break; } } } ServerMessage(content, MessageType.Error); break; } } } }
private void MessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { using (DarkRiftReader r = message.GetReader()) { if (message.Tag == UDRMS_Tags.getLobbyMatchs) { GetLobbyRequestAndSend(e, r); } if (message.Tag == UDRMS_Tags.connectLobbyMatch) { ushort matchToJoin = r.ReadUInt16(); bool canJoin = matchs[matchToJoin].AddPlayerToMatch(players[e.Client]); matchs[matchToJoin].JoinMatch(e.Client, canJoin); } if (message.Tag == UDRMS_Tags.createLobbyMatch) { foreach (Lobby_Match match in matchs.Values) { if (match.matchOwner == players[e.Client]) { //TODO: With Host is Already created a Match Destroy Current Match return; } } CreateMatch(players[e.Client], maxPlayersPerMatch); } if (message.Tag == UDRMS_Tags.refreshLobbyMatchs) { using (DarkRiftWriter w = DarkRiftWriter.Create()) { ushort totalLobbyPages = GetLobbyPages(); w.Write(totalLobbyPages); using (Message m = Message.Create(UDRMS_Tags.refreshLobbyMatchs, w)) e.Client.SendMessage(m, SendMode.Reliable); } } if (message.Tag == UDRMS_Tags.getLobbyMatchInfo) { Lobby_Player lobby_Player = players[e.Client]; if (lobby_Player.getCurrentMatch() != null) { //TODO: connect to match Lobby_Match.SendToPlayerLobbyMatchInformation(lobby_Player); } else { //TODO: Send Player to Lobby or Do Nothing or Send Refresh } } if (message.Tag == UDRMS_Tags.LoginInfo) { string playerName = r.ReadString(); players[e.Client].playerName = playerName; //TODO: Can Login bool canLogin = true; using (DarkRiftWriter w = DarkRiftWriter.Create()) { w.Write(canLogin); using (Message m = Message.Create(UDRMS_Tags.LoginInfo, w)) e.Client.SendMessage(m, SendMode.Reliable); } } } } }
void MessageReceived(object sender, MessageReceivedEventArgs e) { Debug.Log("CreatePlayer entered"); using (Message message = e.GetMessage()) { using (DarkRiftReader reader = message.GetReader()) { if (message.Tag == Tags.CreatePlayerTag) { while (reader.Position < reader.Length) { ushort id = reader.ReadUInt16(); int index = reader.ReadInt32(); Debug.Log(id + " " + index); if (id == client.ID) { if (index == 0) { redPlayerText.text += " Connected"; } else if (index == 1) { bluePlayerText.text += " Connected"; } connected = true; } else { players[index].SetPlayerController(networkPlayers[index]); if (index == 0) { redPlayerText.text += " Connected"; } else if (index == 1) { bluePlayerText.text += " Connected"; } } } } if (message.Tag == Tags.DespawnPlayerTag) { RemovePlayer(sender, e, reader); } else if (message.Tag == Tags.MovePieceTag) { while (reader.Position < reader.Length) { int pieceId = reader.ReadInt32(); float x = reader.ReadSingle(); float z = reader.ReadSingle(); float rotation = reader.ReadSingle(); Transform unitsParentTransform = GameObject.Find("Units").transform; for (int i = 0; i < unitsParentTransform.childCount; i++) { if (pieceId == i) { Transform t = unitsParentTransform.GetChild(i); MovePiece(t, x, z, rotation); break; } } while (reader.Position < reader.Length) { GameObject.Find("RedLaserGun").transform.rotation = new Quaternion(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); GameObject.Find("BlueLaserGun").transform.rotation = new Quaternion(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); } StartCoroutine(TurnEnd()); } } else if (message.Tag == Tags.ChangeLaserDirectionTag) { while (reader.Position < reader.Length) { GameObject.Find("RedLaserGun").transform.rotation = new Quaternion(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); GameObject.Find("BlueLaserGun").transform.rotation = new Quaternion(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); } } } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Login.TagsPerPlugin * RoomTag || message.Tag >= Login.TagsPerPlugin * (RoomTag + 1)) { return; } var client = e.Client; switch (message.Tag) { case Create: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, CreateFailed, "Create Room failed.")) { return; } string roomName; bool isVisible; try { using (var reader = message.GetReader()) { roomName = reader.ReadString(); isVisible = reader.ReadBoolean(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, CreateFailed, ex, "Room Create Failed!"); return; } roomName = AdjustRoomName(roomName, _loginPlugin.UsersLoggedIn[client]); var roomId = GenerateRoomId(); var room = new Room(roomId, roomName, isVisible); var player = new Player(client.ID, _loginPlugin.UsersLoggedIn[client], true); room.AddPlayer(player, client); RoomList.Add(roomId, room); _playersInRooms.Add(client.ID, room); using (var writer = DarkRiftWriter.Create()) { writer.Write(room); writer.Write(player); using (var msg = Message.Create(CreateSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Creating Room " + roomId + ": " + room.Name, LogType.Info); } break; } case Join: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, JoinFailed, "Join Room failed.")) { return; } ushort roomId; try { using (var reader = message.GetReader()) { roomId = reader.ReadUInt16(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, JoinFailed, ex, "Room Join Failed! "); return; } if (!RoomList.ContainsKey(roomId)) { // Return Error 3 for Room doesn't exist anymore using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)3); using (var msg = Message.Create(JoinFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Room Join Failed! Room " + roomId + " doesn't exist anymore", LogType.Info); } return; } var room = RoomList[roomId]; var newPlayer = new Player(client.ID, _loginPlugin.UsersLoggedIn[client], false); // Check if player already is in an active room -> Send error 2 if (_playersInRooms.ContainsKey(client.ID)) { using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(JoinFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent( "User " + client.ID + " couldn't join Room " + room.Id + ", since he already is in Room: " + _playersInRooms[client.ID], LogType.Info); } return; } // Try to join room if (room.AddPlayer(newPlayer, client)) { _playersInRooms[client.ID] = room; using (var writer = DarkRiftWriter.Create()) { writer.Write(room); foreach (var player in room.PlayerList) { writer.Write(player); } using (var msg = Message.Create(JoinSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } // Let the other clients know using (var writer = DarkRiftWriter.Create()) { writer.Write(newPlayer); using (var msg = Message.Create(PlayerJoined, writer)) { foreach (var cl in room.Clients.Where(c => c.ID != client.ID)) { cl.SendMessage(msg, SendMode.Reliable); } } } if (_debug) { WriteEvent("User " + client.ID + " joined Room " + room.Id, LogType.Info); } } // Room full or has started -> Send error 2 else { using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(JoinFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent( "User " + client.ID + " couldn't join, since Room " + room.Id + " was either full or had started!", LogType.Info); } } break; } case Leave: { LeaveRoom(client); break; } case GetOpenRooms: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, GetOpenRoomsFailed, "GetRoomRequest failed.")) { return; } // If he is, send back all available rooms var availableRooms = RoomList.Values.Where(r => r.IsVisible && !r.HasStarted).ToList(); using (var writer = DarkRiftWriter.Create()) { foreach (var room in availableRooms) { writer.Write(room); } using (var msg = Message.Create(GetOpenRooms, writer)) { client.SendMessage(msg, SendMode.Reliable); } } break; } // Start Game Request case StartGame: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, GetOpenRoomsFailed, "Start Game request failed.")) { return; } ushort roomId; try { using (var reader = message.GetReader()) { roomId = reader.ReadUInt16(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, StartGameFailed, ex, "Room Join Failed! "); return; } var username = _loginPlugin.UsersLoggedIn[client]; var player = RoomList[roomId].PlayerList.FirstOrDefault(p => p.Name == username); if (player == null || !player.IsHost) { // Player isn't host of this room -> return error 2 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(StartGameFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("User " + client.ID + " couldn't start the game, since he wasn't a host!", LogType.Warning); } return; } // Start Game - Insert whatever data you need to send to initialize game (f.e. game server connection info) RoomList[roomId].HasStarted = true; using (var msg = Message.CreateEmpty(StartGameSuccess)) { foreach (var cl in RoomList[roomId].Clients) { cl.SendMessage(msg, SendMode.Reliable); } } break; } } } }
void DespawnPlayer(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) networkPlayerManager.DestroyPlayer(reader.ReadUInt16()); }
public void OnClientMessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage()) { if (message.Tag == (ushort)Pkt.PKT_CLIENT_ACCOUNTREGISTERINFO) { PKT_CLIENT_ACCOUNTREGISTERINFO registerInfo = message.Deserialize <PKT_CLIENT_ACCOUNTREGISTERINFO>(); //Check if account already exists if (AccountManager.GetAccount(registerInfo.Username) != null) { PKT_SERVER_ACCOUNTERROR _newError = new PKT_SERVER_ACCOUNTERROR("an account with this username already exists"); e.Client.SendMessage(Message.Create((ushort)Pkt.PKT_SERVER_ACCOUNTERROR, _newError), SendMode.Reliable); return; } Account _newAccount = new Account(registerInfo.Username, registerInfo.Password, registerInfo.Email, registerInfo.Referral); _newAccount.ID = AccountManager.Accounts.Count + 1; AccountManager.AddAccount(_newAccount); AccountManager.Save(); //Tell them they registered. PKT_SERVER_ACCOUNTSUCCESS _newRegisterMessage = new PKT_SERVER_ACCOUNTSUCCESS("Registered, welcome to Project PBBG <color=white>" + registerInfo.Username + "</color>!"); e.Client.SendMessage(Message.Create((ushort)Pkt.PKT_SERVER_ACCOUNTSUCCESS, _newRegisterMessage), SendMode.Reliable); }//Register if (message.Tag == (ushort)Pkt.PKT_CLIENT_ACCOUNTLOGININFO) { PKT_CLIENT_ACCOUNTLOGININFO loginInfo = message.Deserialize <PKT_CLIENT_ACCOUNTLOGININFO>(); if (AccountManager.GetAccount(loginInfo.Username) == null) //Account doesnt exist { PKT_SERVER_ACCOUNTERROR _newError = new PKT_SERVER_ACCOUNTERROR("account with this username doesnt exist"); e.Client.SendMessage(Message.Create((ushort)Pkt.PKT_SERVER_ACCOUNTERROR, _newError), SendMode.Reliable); return; } if (AccountManager.GetAccount(loginInfo.Username).isBanned) //Account is banned { PKT_SERVER_ACCOUNTERROR _newError = new PKT_SERVER_ACCOUNTERROR("account is banned date: length: reason:"); e.Client.SendMessage(Message.Create((ushort)Pkt.PKT_SERVER_ACCOUNTERROR, _newError), SendMode.Reliable); return; } if (AccountManager.isLoggedIn(loginInfo.Username)) //Account is already logged into the game. { PKT_SERVER_ACCOUNTERROR _newError = new PKT_SERVER_ACCOUNTERROR("account already logged in"); e.Client.SendMessage(Message.Create((ushort)Pkt.PKT_SERVER_ACCOUNTERROR, _newError), SendMode.Reliable); return; } AccountManager.LoginAccount(e.Client, AccountManager.GetAccount(loginInfo.Username)); AccountManager.ActiveAccounts[e.Client].NetID = e.Client; TickManager._Tick += AccountManager.ActiveAccounts[e.Client].Tick; if (AccountManager.GetAccount(loginInfo.Username).isNew) { PKT_SERVER_ACCOUNTLOGINSUCCESS _newLoginSuccessMessage = new PKT_SERVER_ACCOUNTLOGINSUCCESS("Character Creation"); e.Client.SendMessage(Message.Create((ushort)Pkt.PKT_SERVER_ACCOUNTLOGINSUCCESS, _newLoginSuccessMessage), SendMode.Reliable); } else { PKT_SERVER_ACCOUNTLOGINSUCCESS _newLoginSuccessMessage = new PKT_SERVER_ACCOUNTLOGINSUCCESS("Game"); e.Client.SendMessage(Message.Create((ushort)Pkt.PKT_SERVER_ACCOUNTLOGINSUCCESS, _newLoginSuccessMessage), SendMode.Reliable); } }//Login } }
static void MessageReceived(object sender, MessageReceivedEventArgs e) { Console.WriteLine("Received a message with tag: " + e.Tag); using (DarkRiftReader reader = e.GetMessage().GetReader()) { if (e.Tag == Tags.HouseNormal) { House _houseNormal = reader.ReadSerializable <House>(); Console.WriteLine("HouseNormal Width is: " + _houseNormal.Width); Console.WriteLine("HouseNormal Height is: " + _houseNormal.Height); Console.WriteLine("HouseNormal Inhabitants is: " + _houseNormal.Inhabitants); } else if (e.Tag == Tags.HouseNothing) { ISync _houseNothing = reader.ReadSerializableSmart(); if (_houseNothing.TypeID == 1) { House _house = (House)_houseNothing; Console.WriteLine("HouseNothing Width is: " + _house.Width); Console.WriteLine("HouseNothing Height is: " + _house.Height); Console.WriteLine("HouseNothing Inhabitants is: " + _house.Inhabitants); } } else if (e.Tag == Tags.HouseType) { House _houseType = reader.ReadSerializableSmart <House>(); Console.WriteLine("HouseType Width is: " + _houseType.Width); Console.WriteLine("HouseType Height is: " + _houseType.Height); Console.WriteLine("HouseType Inhabitants is: " + _houseType.Inhabitants); } else if (e.Tag == Tags.HouseTag) { ISync _houseTag = reader.ReadSerializableSmart(1); if (_houseTag.TypeID == 1) { House _house = (House)_houseTag; Console.WriteLine("HouseTag Width is: " + _house.Width); Console.WriteLine("HouseTag Height is: " + _house.Height); Console.WriteLine("HouseTag Inhabitants is: " + _house.Inhabitants); } } else if (e.Tag == Tags.HouseTypeANDTag) { House _houseTypeANDTag = reader.ReadSerializableSmart <House>(1); Console.WriteLine("HouseTypeANDTag Width is: " + _houseTypeANDTag.Width); Console.WriteLine("HouseTypeANDTag Height is: " + _houseTypeANDTag.Height); Console.WriteLine("HouseTypeANDTag Inhabitants is: " + _houseTypeANDTag.Inhabitants); } else if (e.Tag == Tags.HouseUpdateNothing) { Console.WriteLine("HouseUpdateTag Width was: " + House.Width); Console.WriteLine("HouseUpdateTag Height was: " + House.Height); Console.WriteLine("HouseUpdateTag Inhabitants was: " + House.Inhabitants); House.ReadSerializableSmart(reader); Console.WriteLine("HouseUpdateNothing Width is: " + House.Width); Console.WriteLine("HouseUpdateNothing Height is: " + House.Height); Console.WriteLine("HouseUpdateNothing Inhabitants is: " + House.Inhabitants); } else if (e.Tag == Tags.HouseUpdateTag) { Console.WriteLine("HouseUpdateTag Width was: " + House.Width); Console.WriteLine("HouseUpdateTag Height was: " + House.Height); Console.WriteLine("HouseUpdateTag Inhabitants was: " + House.Inhabitants); House.ReadSerializableSmart(reader, 1); Console.WriteLine("HouseUpdateTag Width is: " + House.Width); Console.WriteLine("HouseUpdateTag Height is: " + House.Height); Console.WriteLine("HouseUpdateTag Inhabitants is: " + House.Inhabitants); } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Login.TagsPerPlugin * GameTag || message.Tag >= Login.TagsPerPlugin * (GameTag + 1)) { return; } var client = e.Client; // Private Message switch (message.Tag) { case InitPlayer: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, MessageFailed, "Init player failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; server.LoadPlayer(senderName); break; } case PlayerShipCommand: { if (!_loginPlugin.PlayerLoggedIn(client, MessageFailed, "Init player failed.")) { return; } ShipCommand command; int target_id; int point_id; try { using (var reader = message.GetReader()) { command = (ShipCommand)reader.ReadUInt32(); target_id = reader.ReadInt32(); point_id = reader.ReadInt32(); } Console.WriteLine("Command {0} target {1}", command, target_id); } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, MessageFailed, ex, "Send Message failed! "); return; } var senderName = _loginPlugin.UsersLoggedIn[client]; server.GetPlayerShipCommand(senderName, command, target_id, point_id); break; } } } }
void MessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { // Server wants to spawn new container if (message.Tag == Tags.SpawnItemContainerTag) { ItemContainerMessage itemContainerMessage = message.Deserialize <ItemContainerMessage>(); GameObject obj = Instantiate(defaultContainer, itemContainerMessage.position, Quaternion.identity) as GameObject; ItemContainer itemContainer = obj.GetComponent <ItemContainer>(); itemContainer.networkID = itemContainerMessage.networkID; itemContainer.itemSpawnManager = this; itemContainerDict.Add(itemContainer.networkID, itemContainer); foreach (ItemMessage item in itemContainerMessage.itemList) { itemContainer.contents.Add(new Item(ItemManager.allItems[item.name], item.amount)); } } // Server wants to add item to container if (message.Tag == Tags.AddItemToContainerTag) { ItemContainerMessage itemContainerMessage = message.Deserialize <ItemContainerMessage>(); ItemContainer itemContainer = itemContainerDict[itemContainerMessage.networkID]; itemContainer.contents.Clear(); foreach (ItemMessage item in itemContainerMessage.itemList) { itemContainer.contents.Add(new Item(ItemManager.allItems[item.name], item.amount)); } } // Server wants to delete item from container if (message.Tag == Tags.DeleteItemFromContainerTag) { ItemContainerMessage itemContainerMessage = message.Deserialize <ItemContainerMessage>(); ItemContainer itemContainer = itemContainerDict[itemContainerMessage.networkID]; itemContainer.contents.Clear(); foreach (ItemMessage item in itemContainerMessage.itemList) { itemContainer.contents.Add(new Item(ItemManager.allItems[item.name], item.amount)); } } // Server wants to transfer items between containers if (message.Tag == Tags.TransferItemBetweenContainersTag) { ItemContainerMessage itemContainerMessage = message.Deserialize <ItemContainerMessage>(); ItemContainer itemContainer = itemContainerDict[itemContainerMessage.networkID]; itemContainer.contents.Clear(); foreach (ItemMessage item in itemContainerMessage.itemList) { itemContainer.contents.Add(new Item(ItemManager.allItems[item.name], item.amount)); } // TODO - this is horrible, should be dealt with by an event? itemContainer.GetComponentInChildren <InventoryPanel>().UpdateItems(); } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Login.TagsPerPlugin * FriendsTag || message.Tag >= Login.TagsPerPlugin * (FriendsTag + 1)) { return; } var client = e.Client; switch (message.Tag) { case FriendRequest: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, RequestFailed, "Friend request failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; string receiver; try { using (var reader = message.GetReader()) { receiver = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, RequestFailed, ex, "Friend Request Failed! "); return; } try { _database.DataLayer.GetFriends(receiver, receiverUser => { if (receiverUser == null) { // No user with that name found -> return error 3 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)3); using (var msg = Message.Create(RequestFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("No user named " + receiver + " found!", LogType.Info); } return; } if (receiverUser.Friends.Contains(senderName) || receiverUser.OpenFriendRequests.Contains(senderName)) { // Users are already friends or have an open request -> return error 4 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)4); using (var msg = Message.Create(RequestFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Request failed, " + senderName + " and " + receiver + " were already friends or had an open friend request!", LogType.Info); } return; } // Save the request in the database to both users _database.DataLayer.AddRequest(senderName, receiver, () => { using (var writer = DarkRiftWriter.Create()) { writer.Write(receiver); using (var msg = Message.Create(RequestSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent(senderName + " wants to add " + receiver + " as a friend!", LogType.Info); } // If Receiver is currently logged in, let him know right away if (_loginPlugin.Clients.ContainsKey(receiver)) { var receivingClient = _loginPlugin.Clients[receiver]; using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); using (var msg = Message.Create(FriendRequest, writer)) { receivingClient.SendMessage(msg, SendMode.Reliable); } } } }); }); } catch (Exception ex) { // Return Error 2 for Database error _database.DatabaseError(client, RequestFailed, ex); } break; } case DeclineRequest: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, DeclineRequestFailed, "DeclineFriendRequest failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; string receiver; try { using (var reader = message.GetReader()) { receiver = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, DeclineRequestFailed, ex, "Decline Request Failed!"); return; } try { // Delete the request from the database for both users _database.DataLayer.RemoveRequest(senderName, receiver, () => { using (var writer = DarkRiftWriter.Create()) { writer.Write(receiver); writer.Write(true); using (var msg = Message.Create(DeclineRequestSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent(senderName + " declined " + receiver + "'s friend request.", LogType.Info); } // If Receiver is currently logged in, let him know right away if (_loginPlugin.Clients.ContainsKey(receiver)) { var receivingClient = _loginPlugin.Clients[receiver]; using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); writer.Write(false); using (var msg = Message.Create(DeclineRequestSuccess, writer)) { receivingClient.SendMessage(msg, SendMode.Reliable); } } } }); } catch (Exception ex) { // Return Error 2 for Database error _database.DatabaseError(client, DeclineRequestFailed, ex); } break; } case AcceptRequest: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, AcceptRequestFailed, "AcceptFriendRequest failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; string receiver; try { using (var reader = message.GetReader()) { receiver = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, AcceptRequestFailed, ex, "Accept Request Failed!"); return; } try { // Delete the request from the database for both users and add their names to their friend list _database.DataLayer.AddFriend(senderName, receiver, () => { var receiverOnline = _loginPlugin.Clients.ContainsKey(receiver); using (var writer = DarkRiftWriter.Create()) { writer.Write(receiver); writer.Write(receiverOnline); using (var msg = Message.Create(AcceptRequestSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent(senderName + " accepted " + receiver + "'s friend request.", LogType.Info); } // If Receiver is currently logged in, let him know right away if (receiverOnline) { var receivingClient = _loginPlugin.Clients[receiver]; using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); writer.Write(true); using (var msg = Message.Create(AcceptRequestSuccess, writer)) { receivingClient.SendMessage(msg, SendMode.Reliable); } } } }); } catch (Exception ex) { // Return Error 2 for Database error _database.DatabaseError(client, AcceptRequestFailed, ex); } break; } case RemoveFriend: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, RemoveFriendFailed, "RemoveFriend failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; string receiver; try { using (var reader = message.GetReader()) { receiver = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, RemoveFriendFailed, ex, "Remove Friend Failed!"); return; } try { // Delete the names from the friendlist in the database for both users _database.DataLayer.RemoveFriend(senderName, receiver, () => { using (var writer = DarkRiftWriter.Create()) { writer.Write(receiver); writer.Write(true); using (var msg = Message.Create(RemoveFriendSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent(senderName + " removed " + receiver + " as a friend.", LogType.Info); } // If Receiver is currently logged in, let him know right away if (_loginPlugin.Clients.ContainsKey(receiver)) { var receivingClient = _loginPlugin.Clients[receiver]; using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); writer.Write(false); using (var msg = Message.Create(RemoveFriendSuccess, writer)) { receivingClient.SendMessage(msg, SendMode.Reliable); } } } }); } catch (Exception ex) { // Return Error 2 for Database error _database.DatabaseError(client, RemoveFriendFailed, ex); } break; } case GetAllFriends: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, GetAllFriendsFailed, "GetAllFriends failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; try { _database.DataLayer.GetFriends(senderName, friendList => { var onlineFriends = new List <string>(); var offlineFriends = new List <string>(); using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); foreach (var friend in friendList.Friends) { if (_loginPlugin.Clients.ContainsKey(friend)) { onlineFriends.Add(friend); // let online friends know he logged in var cl = _loginPlugin.Clients[friend]; using (var msg = Message.Create(FriendLoggedIn, writer)) { cl.SendMessage(msg, SendMode.Reliable); } } else { offlineFriends.Add(friend); } } } using (var writer = DarkRiftWriter.Create()) { writer.Write(onlineFriends.ToArray()); writer.Write(offlineFriends.ToArray()); writer.Write(friendList.OpenFriendRequests.ToArray()); writer.Write(friendList.UnansweredFriendRequests.ToArray()); using (var msg = Message.Create(GetAllFriends, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Got friends for " + senderName, LogType.Info); } }); } catch (Exception ex) { // Return Error 2 for Database error _database.DatabaseError(client, GetAllFriendsFailed, ex); } break; } } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Login.TagsPerPlugin * GameServerTag || message.Tag >= Login.TagsPerPlugin * (GameServerTag + 1)) { return; } var client = e.Client; switch (message.Tag) { case RegisterServer: { IPAddress ip; using (var reader = message.GetReader()) { ip = new IPAddress(reader.ReadBytes()); } // Find an available port List <ushort> ports; if (_portsInUse.ContainsKey(ip)) { ports = _portsInUse[ip]; } else { _portsInUse[ip] = new List <ushort>(); ports = _portsInUse[ip]; } ushort port = 4297; lock (PortLock) { while (ports.Contains(port)) { port++; } ports.Add(port); } GameServers[client] = new Server(ip, port, client); _loginPlugin.UsersLoggedIn.TryRemove(client, out _); using (var writer = DarkRiftWriter.Create()) { writer.Write(port); using (var msg = Message.Create(RegisterServer, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent($"New Server registered at {ip}:{port}", LogType.Info); } break; } case ServerAvailable: GameServers[client].IsAvailable = true; break; case ServerReady: _roomSystem.LoadGame(GameServers[client].Room); break; case Log: { using (var reader = message.GetReader()) { WriteEvent(reader.ReadString(), LogType.Fatal); } break; } } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { NetworkTags tag = (NetworkTags)message.Tag; if (!tag.ToString().StartsWith("TRAIN")) { return; } if (tag != NetworkTags.TRAIN_LOCATION_UPDATE) { Logger.Trace($"[SERVER] < {tag}"); } switch (tag) { case NetworkTags.TRAIN_LEVER: UpdateTrainLever(message, e.Client); break; case NetworkTags.TRAIN_RERAIL: UpdateTrainRerail(message, e.Client); break; case NetworkTags.TRAIN_DERAIL: UpdateTrainDerailed(message, e.Client); break; case NetworkTags.TRAIN_SWITCH: UpdateTrainSwitch(message, e.Client); break; case NetworkTags.TRAIN_COUPLE: UpdateCouplingState(message, e.Client, true); break; case NetworkTags.TRAIN_UNCOUPLE: UpdateCouplingState(message, e.Client, false); break; case NetworkTags.TRAIN_COUPLE_HOSE: UpdateCoupledHoseState(message, e.Client); break; case NetworkTags.TRAIN_COUPLE_COCK: UpdateCoupleCockState(message, e.Client); break; case NetworkTags.TRAIN_SYNC_ALL: SendWorldTrains(e.Client); break; case NetworkTags.TRAIN_HOST_SYNC: SyncTrainDataFromHost(message); break; case NetworkTags.TRAIN_LOCATION_UPDATE: UpdateTrainPosition(message, e.Client); break; case NetworkTags.TRAINS_INIT: NewTrainsInitialized(message, e.Client); break; case NetworkTags.TRAINS_INIT_FINISHED: TrainsFinishedInitilizing(e.Client); break; case NetworkTags.TRAIN_REMOVAL: OnCarRemovalMessage(message, e.Client); break; case NetworkTags.TRAIN_DAMAGE: OnCarDamage(message, e.Client); break; case NetworkTags.TRAIN_AUTH_CHANGE: OnAuthChange(message); break; case NetworkTags.TRAIN_CARGO_CHANGE: OnCargoChange(message, e.Client); break; case NetworkTags.TRAIN_MU_CHANGE: OnCarMUChange(message, e.Client); break; } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Login.TagsPerPlugin * RoomTag || message.Tag >= Login.TagsPerPlugin * (RoomTag + 1)) { return; } var client = e.Client; switch (message.Tag) { case Create: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, CreateFailed, "Create Room failed.")) { return; } string roomName; GameType gameMode; PlayerColor color; bool isVisible; try { using (var reader = message.GetReader()) { roomName = reader.ReadString(); gameMode = (GameType)reader.ReadByte(); isVisible = reader.ReadBoolean(); color = (PlayerColor)reader.ReadByte(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, CreateFailed, ex, "Room Create Failed!"); return; } roomName = AdjustRoomName(roomName, _loginPlugin.UsersLoggedIn[client]); var roomId = GenerateRoomId(); var room = new Room(roomId, roomName, gameMode, isVisible); var player = new Player(client.ID, _loginPlugin.UsersLoggedIn[client], true, color); room.AddPlayer(player, client); RoomList[roomId] = room; _playersInRooms[client.ID] = room; using (var writer = DarkRiftWriter.Create()) { writer.Write(room); writer.Write(player); using (var msg = Message.Create(CreateSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Creating Room " + roomId + ": " + room.Name, LogType.Info); } break; } case Join: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, JoinFailed, "Join Room failed.")) { return; } ushort roomId; PlayerColor color; try { using (var reader = message.GetReader()) { roomId = reader.ReadUInt16(); color = (PlayerColor)reader.ReadByte(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, JoinFailed, ex, "Room Join Failed! "); return; } if (!RoomList.ContainsKey(roomId)) { // Return Error 3 for Room doesn't exist anymore using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)3); using (var msg = Message.Create(JoinFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Room Join Failed! Room " + roomId + " doesn't exist anymore", LogType.Info); } return; } var room = RoomList[roomId]; var newPlayer = new Player(client.ID, _loginPlugin.UsersLoggedIn[client], false, color); // Check if player already is in an active room -> Send error 2 if (_playersInRooms.ContainsKey(client.ID)) { using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(JoinFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("User " + client.ID + " couldn't join Room " + room.Id + ", since he already is in Room: " + _playersInRooms[client.ID], LogType.Info); } return; } // Try to join room if (room.AddPlayer(newPlayer, client)) { // Generate new color if requested one is taken if (room.PlayerList.Exists(p => p.Color == color)) { byte i = 0; while (room.PlayerList.Exists(p => p.Color == (PlayerColor)i)) { i++; } newPlayer.SetNewColor((PlayerColor)i); } _playersInRooms[client.ID] = room; using (var writer = DarkRiftWriter.Create()) { writer.Write(room); foreach (var player in room.PlayerList) { writer.Write(player); } using (var msg = Message.Create(JoinSuccess, writer)) { client.SendMessage(msg, SendMode.Reliable); } } // Let the other clients know using (var writer = DarkRiftWriter.Create()) { writer.Write(newPlayer); using (var msg = Message.Create(PlayerJoined, writer)) { foreach (var cl in room.Clients.Where(c => c.ID != client.ID)) { cl.SendMessage(msg, SendMode.Reliable); } } } if (_debug) { WriteEvent("User " + client.ID + " joined Room " + room.Id, LogType.Info); } } // Room full or has started -> Send error 2 else { using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(JoinFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent( "User " + client.ID + " couldn't join, since Room " + room.Id + " was either full or had started!", LogType.Info); } } break; } case Leave: { LeaveRoom(client); break; } case ChangeColor: { ushort roomId; PlayerColor color; try { using (var reader = message.GetReader()) { roomId = reader.ReadUInt16(); color = (PlayerColor)reader.ReadByte(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, ChangeColorFailed, ex, "Change Color Failed! "); return; } var room = RoomList[roomId]; if (room.PlayerList.Any(p => p.Color == color)) { // Color already taken -> Send error 1 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)1); using (var msg = Message.Create(ChangeColorFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("User " + client.ID + " couldn't change color because it was already taken.", LogType.Info); } } else { room.PlayerList.Find(p => p.Id == client.ID).SetNewColor(color); // Let every other clients know using (var writer = DarkRiftWriter.Create()) { writer.Write(client.ID); writer.Write((byte)color); using (var msg = Message.Create(ChangeColorSuccess, writer)) { foreach (var cl in room.Clients) { cl.SendMessage(msg, SendMode.Reliable); } } } if (_debug) { WriteEvent("User " + client.ID + " successfully changed his color!", LogType.Info); } } break; } case GetOpenRooms: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, GetOpenRoomsFailed, "GetRoomRequest failed.")) { return; } // If he is, send back all available rooms var availableRooms = RoomList.Values.Where(r => r.IsVisible && !r.HasStarted).ToList(); using (var writer = DarkRiftWriter.Create()) { foreach (var room in availableRooms) { writer.Write(room); } using (var msg = Message.Create(GetOpenRooms, writer)) { client.SendMessage(msg, SendMode.Reliable); } } break; } case StartGame: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, GetOpenRoomsFailed, "Start Game request failed.")) { return; } ushort roomId; try { using (var reader = message.GetReader()) { roomId = reader.ReadUInt16(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, StartGameFailed, ex, "Room Join Failed! "); return; } var username = _loginPlugin.UsersLoggedIn[client]; var player = RoomList[roomId].PlayerList.FirstOrDefault(p => p.Name == username); if (player == null || !player.IsHost) { // Player isn't host of this room -> return error 2 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(StartGameFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("User " + client.ID + " couldn't start the game, since he wasn't a host!", LogType.Warning); } return; } // Prepare Gameserver var gameServer = _gameServerPlugin.GameServers.Values.FirstOrDefault(s => s.IsAvailable); if (gameServer == null) { // No GameServer available -> return error 3 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)3); using (var msg = Message.Create(StartGameFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Failed to start game, no game-server available!", LogType.Warning); } return; } RoomList[roomId].HasStarted = true; _gameServerPlugin.StartGame(RoomList[roomId], gameServer); using (var writer = DarkRiftWriter.Create()) { writer.Write(gameServer.Ip.GetAddressBytes()); writer.Write(gameServer.Port); using (var msg = Message.Create(StartGameSuccess, writer)) { foreach (var cl in RoomList[roomId].Clients) { cl.SendMessage(msg, SendMode.Reliable); } } } break; } } } }
void ClientMessageReceived(object sender, MessageReceivedEventArgs e) { //Messages with TRAIN_TAG are for spawning train cars if (e.GetMessage().Tag == TRAIN_TAG) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { int carCount = reader.ReadInt32(); for (int i = 0; i < carCount; i++) { ushort carID = reader.ReadUInt16(); ushort carType = reader.ReadUInt16(); GameObject newCar; switch (carType) { case ENGINE: newCar = Instantiate(enginePrefab); break; case DEFAULT_CAR: newCar = Instantiate(carPrefab); break; case CABOOSE: newCar = Instantiate(caboosePrefab); break; case KITCHEN_CAR: newCar = Instantiate(kitchencarPrefab); break; default: newCar = Instantiate(carPrefab); break; } newCar.transform.parent = train.transform; newCar.transform.rotation = Quaternion.identity; newCar.transform.localPosition = new Vector3(0, 2.9f, -16.13f + 16.13f * i); newCar.GetComponent <NetworkTrackable>().uniqueID = carID; cars.Add(carID, newCar.transform); } } SpawnedTrains = true; } //Message with OBJECT_TAG are for spawning Interactable Objects else if (e.GetMessage().Tag == OBJECT_TAG) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { int objectCount = reader.ReadInt32(); for (int i = 0; i < objectCount; i++) { ushort objID = reader.ReadUInt16(); ushort objType = reader.ReadUInt16(); Vector3 localPosition = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); Vector3 eulerRotation = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); NetworkObject netObj = new NetworkObject(objID, objType, localPosition, eulerRotation); objects.Add(objID, netObj); } } initializedObjects = true; } //Messages with PICKUP_TAG contain the new position and rotation of an object with "Pickup" attached else if (e.GetMessage().Tag == PICKUP_TAG) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { ushort objID = reader.ReadUInt16(); if (objects.ContainsKey(objID)) { GameObject obj = objects[objID].gObj; Vector3 newLocalPosition = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); float angleX = reader.ReadSingle(); float angleY = reader.ReadSingle(); float angleZ = reader.ReadSingle(); obj.transform.localPosition = newLocalPosition; obj.GetComponent <Pickup>().lastPostion = newLocalPosition; Vector3 newRotation = new Vector3(angleX, angleY, angleZ); obj.transform.eulerAngles = newRotation; objects[objID].localPosition = newLocalPosition; objects[objID].rotation = newRotation; } } } //Messages with USE_TAG contain the new use state of an interactable object else if (e.GetMessage().Tag == USE_TAG) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { ushort objID = reader.ReadUInt16(); if (objects.ContainsKey(objID)) { GameObject obj = objects[objID].gObj; ushort useTag = reader.ReadUInt16(); switch (useTag) { case START_USE: obj.GetComponent <Interactable>().StartUse(); break; case DURING_USE: obj.GetComponent <Interactable>().DuringUse(); break; case AFTER_USE: obj.GetComponent <Interactable>().AfterUse(); break; case ABORT_USE: obj.GetComponent <Interactable>().AbortUse(); break; } } else { Debug.LogWarning("Warning, received ID does not match an object"); } } } else if (e.GetMessage().Tag == NUM_PLAYERS_TAG) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { int numPlayers = reader.ReadInt32(); numPlayerText.text = "Players: " + numPlayers.ToString(); } } else if (e.GetMessage().Tag == DESTROY_OBJ_TAG) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { ushort objID = reader.ReadUInt16(); GameObject toDestroy = objects[objID].gObj; Destroy(toDestroy); objects.Remove(objID); } } else if (e.GetMessage().Tag == SPAWN_OBJ_TAG) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { ushort objID = reader.ReadUInt16(); ushort objType = reader.ReadUInt16(); Vector3 localPosition = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); Vector3 eulerRotation = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); NetworkObject netObj = new NetworkObject(objID, objType, localPosition, eulerRotation); GameObject newObj; switch (netObj.ObjType) { case 0: newObj = Instantiate(testInteractablePrefab, train.transform.TransformPoint(netObj.localPosition), Quaternion.Euler(netObj.rotation.x, netObj.rotation.y, netObj.rotation.z), train.transform); break; case 1: newObj = Instantiate(testPickupPrefab, train.transform.TransformPoint(netObj.localPosition), Quaternion.Euler(netObj.rotation.x, netObj.rotation.y, netObj.rotation.z), train.transform); newObj.GetComponent <Pickup>().lastPostion = train.transform.InverseTransformPoint(netObj.localPosition); newObj.GetComponent <Pickup>().ID = netObj.ID; break; default: newObj = Instantiate(testInteractablePrefab, train.transform.TransformPoint(netObj.localPosition), Quaternion.Euler(netObj.rotation.x, netObj.rotation.y, netObj.rotation.z), train.transform); break; } newObj.GetComponent <NetworkTrackable>().uniqueID = netObj.ID; objects.Add(objID, netObj); } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Login.TagsPerPlugin * ChatTag || message.Tag >= Login.TagsPerPlugin * (ChatTag + 1)) { return; } var client = e.Client; // Private Message switch (message.Tag) { case PrivateMessage: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, MessageFailed, "Private Message failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; string receiver; string content; try { using (var reader = message.GetReader()) { receiver = reader.ReadString(); content = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, MessageFailed, ex, "Send Message failed! "); return; } if (!_loginPlugin.Clients.ContainsKey(receiver)) { // If receiver isn't logged in -> return error 3 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)3); using (var msg = Message.Create(MessageFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Send Message failed. Receiver wasn't logged in.", LogType.Info); } return; } var receivingClient = _loginPlugin.Clients[receiver]; // Let sender know message got transmitted using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); writer.Write(receiver); writer.Write(content); using (var msg = Message.Create(SuccessfulPrivateMessage, writer)) { client.SendMessage(msg, SendMode.Reliable); } } // Let receiver know about the new message using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); writer.Write(content); using (var msg = Message.Create(PrivateMessage, writer)) { receivingClient.SendMessage(msg, SendMode.Reliable); } } break; } case RoomMessage: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, MessageFailed, "Group/Room Message failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; ushort roomId; string content; try { using (var reader = message.GetReader()) { roomId = reader.ReadUInt16(); content = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, MessageFailed, ex, "Send Message failed! "); return; } if (!_roomSystem.RoomList[roomId].Clients.Contains(client)) { // If player isn't actually in the room -> return error 2 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(MessageFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } WriteEvent("Send Message failed. Player wasn't part of the room.", LogType.Warning); return; } using (var writer = DarkRiftWriter.Create()) { writer.Write(senderName); writer.Write(content); using (var msg = Message.Create(RoomMessage, writer)) { foreach (var cl in _roomSystem.RoomList[roomId].Clients) { cl.SendMessage(msg, SendMode.Reliable); } } } break; } case GroupMessage: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, MessageFailed, "Group/Room Message failed.")) { return; } var senderName = _loginPlugin.UsersLoggedIn[client]; string groupName; string content; try { using (var reader = message.GetReader()) { groupName = reader.ReadString(); content = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, MessageFailed, ex, "Send Message failed! "); return; } if (!ChatGroups[groupName].Users.Values.Contains(client)) { // If player isn't actually in the chatgroup -> return error 2 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(MessageFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } WriteEvent("Send Message failed. Player wasn't part of the chat group.", LogType.Warning); return; } using (var writer = DarkRiftWriter.Create()) { writer.Write(groupName); writer.Write(senderName); writer.Write(content); using (var msg = Message.Create(GroupMessage, writer)) { foreach (var cl in ChatGroups[groupName].Users.Values) { cl.SendMessage(msg, SendMode.Reliable); } } } break; } case JoinGroup: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, JoinGroupFailed, "Join ChatGroup failed.")) { return; } var playerName = _loginPlugin.UsersLoggedIn[client]; string groupName; try { using (var reader = message.GetReader()) { groupName = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, JoinGroupFailed, ex, "Join Chatgroup failed! "); return; } // Create chatgroup if necessary and add player to it var chatGroup = ChatGroups.FirstOrDefault(x => string.Equals(x.Key, groupName, StringComparison.CurrentCultureIgnoreCase)).Value; if (chatGroup == null) { chatGroup = new ChatGroup(groupName); ChatGroups[groupName] = chatGroup; } if (!chatGroup.AddPlayer(playerName, client)) { // Already in Chatgroup -> return error 2 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(JoinGroupFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } return; } if (!ChatGroupsOfPlayer.ContainsKey(playerName)) { ChatGroupsOfPlayer[playerName] = new List <ChatGroup>(); } ChatGroupsOfPlayer[playerName].Add(chatGroup); using (var writer = DarkRiftWriter.Create()) { writer.Write(chatGroup); using (var msg = Message.Create(JoinGroup, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Player joined ChatGroup: " + groupName, LogType.Info); } break; } case LeaveGroup: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, JoinGroupFailed, "Leave ChatGroup failed.")) { return; } var playerName = _loginPlugin.UsersLoggedIn[client]; string groupName; try { using (var reader = message.GetReader()) { groupName = reader.ReadString(); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved _loginPlugin.InvalidData(client, JoinGroupFailed, ex, "Leave ChatGroup failed! "); return; } // get chatgroup if necessary and remove player from it var chatGroup = ChatGroups.FirstOrDefault(x => string.Equals(x.Key, groupName, StringComparison.CurrentCultureIgnoreCase)).Value; if (chatGroup == null) { // No such Chatgroup -> return error 2 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)2); using (var msg = Message.Create(LeaveGroupFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } return; } chatGroup.RemovePlayer(playerName); // Remove Chatgroup if he was the last player in it if (chatGroup.Users.Count == 0 && chatGroup.Name != "General") { ChatGroups.Remove(chatGroup.Name); } // Remove chatgroup from the players groups if (ChatGroupsOfPlayer[playerName].Count == 0) { ChatGroupsOfPlayer.Remove(playerName); } else { ChatGroupsOfPlayer[playerName].Remove(chatGroup); } using (var writer = DarkRiftWriter.Create()) { writer.Write(chatGroup.Name); using (var msg = Message.Create(LeaveGroup, writer)) { client.SendMessage(msg, SendMode.Reliable); } } if (_debug) { WriteEvent("Player left ChatGroup: " + groupName, LogType.Info); } break; } case GetActiveGroups: { // If player isn't logged in -> return error 1 if (!_loginPlugin.PlayerLoggedIn(client, GetActiveGroupsFailed, "Get ChatGroups failed.")) { return; } var groupNames = ChatGroups.Values.Select(chatGroup => chatGroup.Name).ToArray(); using (var writer = DarkRiftWriter.Create()) { writer.Write(groupNames); using (var msg = Message.Create(GetActiveGroups, writer)) { client.SendMessage(msg, SendMode.Reliable); } } break; } } } }
void Client_MessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { using (DarkRiftReader r = message.GetReader()) { if (message.Tag == UDRMS_Tags.connectedToMS) { //TODO: Login MenuCanvas_Controller.Instance.ActiveLogin(); } if (message.Tag == UDRMS_Tags.LoginInfo) { bool canLogin = r.ReadBoolean(); if (canLogin) { Player_Manager.Instance.SetState(ClientState.AtLobbyScreen); } else { //TODO: Refresh Login } } if (message.Tag == UDRMS_Tags.getLobbyMatchs) { MenuCanvas_Controller.Instance.ClearMatchLobbys_Lobby(); while (r.Position < r.Length) { ushort matchID = r.ReadUInt16(); ushort matchOwnerID = r.ReadUInt16(); ushort actualPlayers = r.ReadUInt16(); ushort maxPlayersInMatch = r.ReadUInt16(); MenuCanvas_Controller.Instance.AddMatchLobby_Lobby(matchID); } } if (message.Tag == UDRMS_Tags.createLobbyMatch) { } if (message.Tag == UDRMS_Tags.getLobbyMatchInfo) { } //Connectou-se ao Lobby da Partida if (message.Tag == UDRMS_Tags.connectLobbyMatch) { bool canJoin = r.ReadBoolean(); ushort matchID = r.ReadUInt16(); if (canJoin) { //TODO: Move to Room Player_Manager.Instance.SetState(ClientState.AtLobbyMatchScreen); } } } } }
private void SpawnMessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { if (message.Tag == Tags.SpawnPlayerTag) { using (DarkRiftReader reader = message.GetReader()) { while (reader.Position < reader.Length) { PlayerSpawnClientDTO clientSpawnData = reader.ReadSerializable <PlayerSpawnClientDTO>(); WorldData World = WorldManager.clients[e.Client].World; ushort entityId = clientSpawnData.entityID; bool isNewPlayer = clientSpawnData.isAI ? !World.AIPlayers.ContainsKey(clientSpawnData.PlayerID) : !World.players.ContainsKey(e.Client); Player player; //TODO: use spawn rotation and health if (isNewPlayer) { player = new Player( clientSpawnData.isAI ? World.aiIDCounter : e.Client.ID, //Player id clientSpawnData.position.x, clientSpawnData.position.y, clientSpawnData.position.z, //Position x,y,z TODO: make this a UMVector3 entityId, 100f, // MaxHealth clientSpawnData.isAI ); if (clientSpawnData.isAI) { World.AIPlayers.Add(World.aiIDCounter, player); World.aiIDCounter++; } else { World.players.Add(e.Client, player); } } else { player = clientSpawnData.isAI ? World.AIPlayers[clientSpawnData.PlayerID] : World.players[e.Client]; player.entityId = clientSpawnData.entityID; player.X = clientSpawnData.position.x; player.Y = clientSpawnData.position.y; player.Z = clientSpawnData.position.z; } Console.WriteLine($"{player.ID} ({e.Client.ID}) requested spawn. isNewPlayer {isNewPlayer}, entityID { player.entityId }"); using (DarkRiftWriter newPlayerWriter = DarkRiftWriter.Create()) { this.WritePlayerSpawnData(newPlayerWriter, player); using (Message newPlayerMessage = Message.Create(Tags.SpawnPlayerTag, newPlayerWriter)) { foreach (IClient client in World.GetClients()) { client.SendMessage(newPlayerMessage, SendMode.Reliable); } } } } } } } }
void DarkRift_MessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { if (OverallStateManager.Instance.OverallState == OverallState.IN_GAME) { if (ClientGameManager.Instance.ClientState == GameStates.GAME_IN_PROGRESS || ClientGameManager.Instance.ClientState == GameStates.WAITING_FOR_PLAYERS) { //game is in progress if (message.Tag == NetworkTags.EntityUpdate) { ClientEntityManager entityManager = ClientEntityManager.Instance; while (reader.Position < reader.Length) { string entityId = reader.ReadString(); string entityTypeId = reader.ReadString(); Entity entity = entityManager.GetEntity(entityId); if (entity == null) { entity = entityManager.CreateEntity(entityTypeId); reader.ReadSerializableInto(ref entity); //must populate entity before registering since registration depends on entity data entityManager.RegisterEntity(entity); } else { reader.ReadSerializableInto(ref entity); } } } else if (message.Tag == NetworkTags.PlayerEventUpdate) { ClientEntityManager entityManager = ClientEntityManager.Instance; while (reader.Position < reader.Length) { string playerEventId = reader.ReadString(); string playerEventTypeId = reader.ReadString(); PlayerEvent playerEvent = entityManager.GetPlayerEvent(playerEventId); if (playerEvent == null) { playerEvent = entityManager.CreatePlayerEvent(playerEventTypeId); reader.ReadSerializableInto(ref playerEvent); //must populate event before registering since registration depends on event data entityManager.RegisterPlayerEvent(playerEvent); } else { reader.ReadSerializableInto(ref playerEvent); } } } else if (message.Tag == NetworkTags.EntityDeath) { ClientEntityManager.Instance.HandleEntityDeath(reader.ReadString()); } else if (message.Tag == NetworkTags.EntityDespawn) { ClientEntityManager.Instance.HandleEntityDespawn(reader.ReadString()); } else if (message.Tag == NetworkTags.PlayerEventEnd) { ClientEntityManager.Instance.HandlePlayerEventEnd(reader.ReadString()); } else if (message.Tag == NetworkTags.CapturePoint) { while (reader.Position < reader.Length) { CapturePoint capturePoint = ClientGameManager.Instance.CapturePoints[reader.ReadUInt16()]; reader.ReadSerializableInto(ref capturePoint); } } else if (message.Tag == NetworkTags.GameState) { ClientGameManager.Instance.UpdateGameState(reader.ReadSerializable <GameState>(), reader.ReadBoolean()); } } if (message.Tag == NetworkTags.ChatMessage) { UIManager.Instance.AddChatMessage(ClientGameManager.Instance.GameState.GetPlayer(reader.ReadString()), reader.ReadString()); } else if (message.Tag == NetworkTags.UnitList) { List <PlayerUnit> playerUnits = new List <PlayerUnit>(); while (reader.Position < reader.Length) { playerUnits.Add(reader.ReadSerializable <PlayerUnit>()); } UIManager.Instance.OnUnitListReceived(playerUnits); } else if (message.Tag == NetworkTags.PlayerJoined) { ClientGameManager.Instance.OnPlayerJoined(reader.ReadSerializable <Player>()); } else if (message.Tag == NetworkTags.PlayerLeft) { ClientGameManager.Instance.OnPlayerLeft(reader.ReadSerializable <Player>()); } } else if (OverallStateManager.Instance.OverallState != OverallState.IN_GAME) { if (waitingToJoin) { if (message.Tag == NetworkTags.GameState) { waitingToJoin = false; OverallStateManager.Instance.LoadGame(reader.ReadSerializable <GameState>(), reader.ReadBoolean()); } } else { if (message.Tag == NetworkTags.FullUnitList) { List <PlayerUnit> playerUnits = new List <PlayerUnit>(); while (reader.Position < reader.Length) { playerUnits.Add(reader.ReadSerializable <PlayerUnit>()); } MainMenuManager.Instance.OnUnitListReceived(playerUnits); } } } if (message.Tag == NetworkTags.Connection) { //Response to join request indicating if our matchmaking ticket was valid if (reader.ReadBoolean()) { IsConnectedToServer = true; //Notify anyone interested that we've completed joining a server Debug.Log("PlayFab: Ticket accepted by server, join completed."); ServerJoinSuccess?.Invoke("PlayFab: Ticket accepted by server, join completed."); } else { Debug.LogError("PlayFab: Ticket rejected by server, disconnecting."); ServerJoinFailure?.Invoke("PlayFab: Ticket rejected by server, disconnecting."); client.Disconnect(); } } } }
private void OnClientMessageReceived(object sender, MessageReceivedEventArgs e) { switch (e.Tag) { case (ushort)tags.Tag.SET_NAME: // Registering new player using (Message message = e.GetMessage()) { using (DarkRiftReader reader = message.GetReader()) { string name = reader.ReadString(); Console.WriteLine("Hello " + name, ConsoleColor.Green); Player newPlayer = new Player(e.Client, name); if (pendingPlayer == null) { // Player is waiting for a match pendingPlayer = newPlayer; } else { // start a new match if there's a player waiting Match match = new Match(pendingPlayer, newPlayer); matches.Add(match.id, match); Console.WriteLine("The match has been added and its ID is: " + match.id); // send a message that match has been found using (DarkRiftWriter writer = DarkRiftWriter.Create()) { writer.Write(match.id); Console.WriteLine("The match has been wrote and its ID is: " + match.id); using (Message connectedMessage = Message.Create((ushort)tags.Tag.MATCH_CONNECTED, writer)) { //Reliable TCP //Unreliable UDP pendingPlayer.Client.SendMessage(connectedMessage, SendMode.Reliable); newPlayer.Client.SendMessage(connectedMessage, SendMode.Reliable); Console.WriteLine("The messages have been sent and the match ID is: " + match.id); } } pendingPlayer = null; } } } break; case (ushort)tags.Tag.SPACE_TAKEN: using (Message message = e.GetMessage()) { using (DarkRiftReader reader = message.GetReader()) { ushort matchId = reader.ReadUInt16(); ushort spaceTaken = reader.ReadUInt16(); if (matches.ContainsKey(matchId)) { Match match = matches[matchId]; match.PlayerSpaceClicked(spaceTaken, e.Client); } } } break; } }
private static void OnDataHandler(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag < Tags.TagsPerPlugin * Tags.Friends || message.Tag >= Tags.TagsPerPlugin * (Tags.Friends + 1)) { return; } switch (message.Tag) { // New friend request received case FriendTags.FriendRequest: { using (var reader = message.GetReader()) { var friendName = reader.ReadString(); ChatManager.ServerMessage(friendName + " wants to add you as a friend!", MessageType.Info); onNewFriendRequest?.Invoke(friendName); } break; } case FriendTags.RequestSuccess: { using (var reader = message.GetReader()) { var friendName = reader.ReadString(); ChatManager.ServerMessage("Friend request sent.", MessageType.Info); onSuccessfulFriendRequest?.Invoke(friendName); } break; } case FriendTags.RequestFailed: { var content = "Failed to send friend request."; using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid RequestFailed Error data received."); } else { switch (reader.ReadByte()) { case 0: Debug.Log("Invalid Friend Request data sent!"); break; case 1: Debug.Log("Player not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("Database Error"); break; case 3: Debug.Log("No user with that name found!"); content = "Username doesn't exist."; break; case 4: Debug.Log("Friend request failed. You are already friends or have an open request"); content = "You are already friends or have an open request with this player."; break; default: Debug.Log("Invalid errorId!"); break; } } ChatManager.ServerMessage(content, MessageType.Error); } break; } case FriendTags.DeclineRequestSuccess: { using (var reader = message.GetReader()) { var friendName = reader.ReadString(); var isSender = reader.ReadBoolean(); var content = isSender ? "Declined " + friendName + "'s friend request." : friendName + " declined your friend request."; ChatManager.ServerMessage(content, MessageType.Error); onSuccessfulDeclineRequest?.Invoke(friendName); } break; } case FriendTags.DeclineRequestFailed: { ChatManager.ServerMessage("Failed to decline request.", MessageType.Error); using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid DeclineRequestFailed Error data received."); return; } switch (reader.ReadByte()) { case 0: Debug.Log("Invalid Decline Request data sent!"); break; case 1: Debug.Log("Player not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("Database Error"); break; default: Debug.Log("Invalid errorId!"); break; } break; } } case FriendTags.AcceptRequestSuccess: { using (var reader = message.GetReader()) { var friendName = reader.ReadString(); var isSender = reader.ReadBoolean(); ChatManager.ServerMessage("Added " + friendName + " to your friendlist.", MessageType.Info); onSuccessfulAcceptRequest?.Invoke(friendName, isSender); } break; } case FriendTags.AcceptRequestFailed: { ChatManager.ServerMessage("Failed to accept request.", MessageType.Error); using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid DeclineRequestFailed Error data received."); return; } switch (reader.ReadByte()) { case 0: Debug.Log("Invalid Accept Request data sent!"); break; case 1: Debug.Log("Player not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("Database Error"); break; default: Debug.Log("Invalid errorId!"); break; } } break; } case FriendTags.RemoveFriendSuccess: { using (var reader = message.GetReader()) { var friendName = reader.ReadString(); var isSender = reader.ReadBoolean(); var content = isSender ? "Removed " + friendName + " from your friendlist." : friendName + " removed you from his friendlist."; ChatManager.ServerMessage(content, MessageType.Error); onSuccessfulRemoveFriend?.Invoke(friendName); } break; } case FriendTags.RemoveFriendFailed: { ChatManager.ServerMessage("Failed to remove friend.", MessageType.Error); using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid RemoveFriend Error data received."); return; } switch (reader.ReadByte()) { case 0: Debug.Log("Invalid Remove Friend data sent!"); break; case 1: Debug.Log("Player not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("Database Error"); break; default: Debug.Log("Invalid errorId!"); break; } } break; } case FriendTags.GetAllFriends: { using (var reader = message.GetReader()) { var onlineFriends = reader.ReadStrings(); var offlineFriends = reader.ReadStrings(); var openRequests = reader.ReadStrings(); var unansweredRequests = reader.ReadStrings(); foreach (var friend in onlineFriends) { ChatManager.ServerMessage(friend + " is online.", MessageType.Info); } onSuccessfulGetAllFriends?.Invoke(onlineFriends, offlineFriends, openRequests, unansweredRequests); } break; } case FriendTags.GetAllFriendsFailed: { ChatManager.ServerMessage("Failed to load Friendlist!", MessageType.Error); using (var reader = message.GetReader()) { if (reader.Length != 1) { Debug.LogWarning("Invalid RemoveFriend Error data received."); return; } switch (reader.ReadByte()) { case 1: Debug.Log("Player not logged in!"); SceneManager.LoadScene("Login"); break; case 2: Debug.Log("Database Error"); break; default: Debug.Log("Invalid errorId!"); break; } } break; } case FriendTags.FriendLoggedIn: { using (var reader = message.GetReader()) { var friendName = reader.ReadString(); ChatManager.ServerMessage(friendName + " is online.", MessageType.Info); onFriendLogin?.Invoke(friendName); } break; } case FriendTags.FriendLoggedOut: { using (var reader = message.GetReader()) { var friendName = reader.ReadString(); ChatManager.ServerMessage(friendName + " is offline.", MessageType.Info); onFriendLogout?.Invoke(friendName); } break; } } } }
void ItemMessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { // Client wants to add item to container if (message.Tag == Tags.AddItemToContainerTag) { using (DarkRiftReader reader = message.GetReader()) { int networkID = reader.ReadInt32(); string itemName = reader.ReadString(); int amount = reader.ReadInt32(); NetworkItemContainer.itemContainerDictionary[networkID].AddItem(CreateItem(itemName, amount)); using (Message newMessage = Message.Create(Tags.AddItemToContainerTag, NetworkItemContainer.itemContainerDictionary[networkID])) { foreach (IClient c in ClientManager.GetAllClients()) { c.SendMessage(newMessage, SendMode.Reliable); } } } } // Client wants to delete item from container if (message.Tag == Tags.DeleteItemFromContainerTag) { using (DarkRiftReader reader = message.GetReader()) { int networkID = reader.ReadInt32(); string itemName = reader.ReadString(); int amount = reader.ReadInt32(); NetworkItemContainer.itemContainerDictionary[networkID].DeleteItem(CreateItem(itemName, amount)); using (Message newMessage = Message.Create(Tags.DeleteItemFromContainerTag, NetworkItemContainer.itemContainerDictionary[networkID])) { foreach (IClient c in ClientManager.GetAllClients()) { c.SendMessage(newMessage, SendMode.Reliable); } } } } // Client wants to transfer item from one container to another if (message.Tag == Tags.TransferItemBetweenContainersTag) { using (DarkRiftReader reader = message.GetReader()) { int fromContainerNetworkID = reader.ReadInt32(); int toContainerNetworkID = reader.ReadInt32(); string itemName = reader.ReadString(); int amount = reader.ReadInt32(); TransferItemBetweenContainers(CreateItem(itemName, amount), NetworkItemContainer.itemContainerDictionary[fromContainerNetworkID], NetworkItemContainer.itemContainerDictionary[toContainerNetworkID]); // Update the donor container using (Message newMessage = Message.Create(Tags.TransferItemBetweenContainersTag, NetworkItemContainer.itemContainerDictionary[fromContainerNetworkID])) { foreach (IClient c in ClientManager.GetAllClients()) { c.SendMessage(newMessage, SendMode.Reliable); } } // Update the receiver container using (Message newMessage = Message.Create(Tags.TransferItemBetweenContainersTag, NetworkItemContainer.itemContainerDictionary[toContainerNetworkID])) { foreach (IClient c in ClientManager.GetAllClients()) { c.SendMessage(newMessage, SendMode.Reliable); } } } } } }
private void PlayerUpdateMessageRecieved(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage() as Message) { if (message.Tag == Tags.PlayerUpdateTag) { using (DarkRiftReader reader = message.GetReader()) { while (reader.Position < reader.Length) { WorldData World = WorldManager.clients[e.Client].World; PlayerUpdateClientDTO playerUpdateData = reader.ReadSerializable <PlayerUpdateClientDTO>(); Player player; if (playerUpdateData.PlayerID < 128) { player = World.players[e.Client]; } else { player = World.AIPlayers[playerUpdateData.PlayerID]; } player.X = playerUpdateData.x; player.Y = playerUpdateData.y; player.Z = playerUpdateData.z; player.RX = playerUpdateData.rx; player.RY = playerUpdateData.ry; player.RZ = playerUpdateData.rz; player.VX = playerUpdateData.vx; player.VY = playerUpdateData.vy; player.VZ = playerUpdateData.vz; using (DarkRiftWriter writer = DarkRiftWriter.Create()) { PlayerUpdateServerDTO playerUpdateOutData = new PlayerUpdateServerDTO(); playerUpdateOutData.ID = player.ID; playerUpdateOutData.x = player.X; playerUpdateOutData.y = player.Y; playerUpdateOutData.z = player.Z; playerUpdateOutData.rx = player.RX; playerUpdateOutData.ry = player.RY; playerUpdateOutData.rz = player.RZ; playerUpdateOutData.vx = player.VX; playerUpdateOutData.vy = player.VY; playerUpdateOutData.vz = player.VZ; playerUpdateOutData.triggerQueue = playerUpdateData.triggerQueue; writer.Write(playerUpdateOutData); using (Message playerUpdateMessage = Message.Create(Tags.PlayerUpdateTag, writer)) { foreach (IClient c in World.GetClients().Where(x => x != e.Client)) { c.SendMessage(playerUpdateMessage, e.SendMode); } } } } } } } }
private void OnClientMessageReceived(object sender, MessageReceivedEventArgs e) { switch (e.Tag) { case (ushort)Tags.Tag.SET_NAME: // new player registering using (Message message = e.GetMessage()) { using (DarkRiftReader reader = message.GetReader()) { string name = reader.ReadString(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("hey mister " + name); Console.ForegroundColor = ConsoleColor.White; PlayerModel newPlayer = new PlayerModel(e.Client, name); if (pendingPlayer == null) { // new player is pending for a match pendingPlayer = newPlayer; } else { // there is already a pending player. lets start a new match MatchModel match = new MatchModel(pendingPlayer, newPlayer); matches.Add(match.id, match); // report clients of the new match using (DarkRiftWriter writer = DarkRiftWriter.Create()) { writer.Write(match.id); writer.Write(match.CurrentPlayerClientID); using (Message msg = Message.Create((ushort)Tags.Tag.GOT_MATCH, writer)) { pendingPlayer.Client.SendMessage(msg, SendMode.Reliable); newPlayer.Client.SendMessage(msg, SendMode.Reliable); } } pendingPlayer = null; } } } break; case (ushort)Tags.Tag.SLATE_TAKEN: using (Message message = e.GetMessage()) { using (DarkRiftReader reader = message.GetReader()) { ushort matchId = reader.ReadUInt16(); ushort slateIndex = reader.ReadUInt16(); if (matches.ContainsKey(matchId)) { MatchModel match = matches[matchId]; match.PlayerTakesSlate(slateIndex, e.Client); if (match.MatchOver) { // match is over Console.WriteLine($"match over. had: {matches.Count} matches"); matches.Remove(matchId); Console.WriteLine($"match over. now have: {matches.Count} matches"); } } } } break; } }
public void Client_MessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage()) { #region all clients if (message.Tag == Tags.ChangeScene) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.ChangeSceneWithReply) { _plugin.BroadcastToAllClients(message, e); using (DarkRiftReader reader = message.GetReader()) { ushort sceneId = reader.ReadUInt16(); if (sceneId == 2) { _plugin.gameInProgress = false; } } } if (message.Tag == Tags.GameStarted) { _plugin.gameInProgress = true; _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.UpdateLobby) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.SpawnCharacter) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.LevelGraph) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.EndLevelTrigger) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.CloseDoorsMessage) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.OpenDoorsMessage) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.DisposeCharacter) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.SpawnPickup) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.DespawnPickup) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.AssignItem) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.WeaponChanged) { _plugin.BroadcastToAllClients(message, e); } if (message.Tag == Tags.UpdateGameState) { _plugin.BroadcastToAllClients(message, e); } #endregion #region other clients if (message.Tag == Tags.SpawnAI) { _plugin.BroadcastToOtherClients(message, e); } if (message.Tag == Tags.DespawnAI) { _plugin.BroadcastToOtherClients(message, e); } if (message.Tag == Tags.UpdateCharacterState) { _plugin.BroadcastToOtherClients(message, e); } if (message.Tag == Tags.UpdateCharacterEquipment) { _plugin.BroadcastToOtherClients(message, e); } if (message.Tag == Tags.DespawnCharacter) { _plugin.BroadcastToOtherClients(message, e); } if (message.Tag == Tags.TakeDamage) { _plugin.BroadcastToOtherClients(message, e); } if (message.Tag == Tags.UpdateHealth) { _plugin.BroadcastToOtherClients(message, e); } if (message.Tag == Tags.SpawnProjectile) { _plugin.BroadcastToOtherClients(message, e); } #endregion #region host only if (message.Tag == Tags.PlayerJoined) { _plugin.BroadcastToHost(message, e); } if (message.Tag == Tags.IsPlayerReady) { _plugin.BroadcastToHost(message, e); } if (message.Tag == Tags.RequestUpdateLobby) { _plugin.BroadcastToHost(message, e); } if (message.Tag == Tags.SceneReady) { _plugin.BroadcastToHost(message, e); } if (message.Tag == Tags.ClientReady) { _plugin.BroadcastToHost(message, e); } if (message.Tag == Tags.DeathRequest) { _plugin.BroadcastToHost(message, e); } if (message.Tag == Tags.RemoveItem) { _plugin.BroadcastToHost(message, e); } if (message.Tag == Tags.RequestSpawnPickup) { _plugin.BroadcastToHost(message, e); } #endregion if (message.Tag == Tags.LoadLobby) { using (DarkRiftReader reader = message.GetReader()) { ushort id = reader.ReadUInt16(); _plugin.BroadcastToClient(message, e, id); } } } }
private void OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (var message = e.GetMessage()) { // Check if message is meant for this plugin if (message.Tag >= TagsPerPlugin * (LoginTag + 1)) { return; } var client = e.Client; switch (message.Tag) { case LoginUser: { // If user is already logged in (shouldn't happen though) if (UsersLoggedIn[client] != null) { using (var msg = Message.CreateEmpty(LoginSuccess)) { client.SendMessage(msg, SendMode.Reliable); } return; } string username; string password; using (var reader = message.GetReader()) { try { username = reader.ReadString(); password = Encryption.Decrypt(reader.ReadBytes(), _privateKey); } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved InvalidData(client, LoginFailed, ex, "Failed to log in!"); return; } } if (Clients.ContainsKey(username)) { // Username is already in use -> return Error 3 using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)3); using (var msg = Message.Create(LoginFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } return; } try { _database.DataLayer.GetUser(username, user => { if (user != null && BCrypt.Net.BCrypt.Verify(password, user.Password)) { UsersLoggedIn[client] = username; Clients[username] = client; using (var msg = Message.CreateEmpty(LoginSuccess)) { client.SendMessage(msg, SendMode.Reliable); } if (_debug) { WriteEvent("Successful login (" + client.ID + ").", LogType.Info); } } else { if (_debug) { WriteEvent("User " + client.ID + " couldn't log in!", LogType.Info); } // Return Error 1 for "Wrong username/password combination" using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)1); using (var msg = Message.Create(LoginFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } } }); } catch (Exception ex) { // Return Error 2 for Database error _database.DatabaseError(client, LoginFailed, ex); } break; } case LogoutUser: { var username = UsersLoggedIn[client]; UsersLoggedIn[client] = null; if (username != null) { Clients.TryRemove(username, out _); } if (_debug) { WriteEvent("User " + client.ID + " logged out!", LogType.Info); } using (var msg = Message.CreateEmpty(LogoutSuccess)) { client.SendMessage(msg, SendMode.Reliable); } onLogout?.Invoke(username); break; } case AddUser: { if (!_allowAddUser) { return; } string username; string password; try { using (var reader = message.GetReader()) { username = reader.ReadString(); password = BCrypt.Net.BCrypt.HashPassword( Encryption.Decrypt(reader.ReadBytes(), _privateKey) , 10); } } catch (Exception ex) { // Return Error 0 for Invalid Data Packages Recieved InvalidData(client, AddUserFailed, ex, "Failed to add user!"); return; } try { _database.DataLayer.UsernameAvailable(username, isAvailable => { if (isAvailable) { _database.DataLayer.AddNewUser(username, password, () => { if (_debug) { WriteEvent("New User: "******"New User: "******"User " + client.ID + " failed to sign up!", LogType.Info); } // Return Error 1 for "Wrong username/password combination" using (var writer = DarkRiftWriter.Create()) { writer.Write((byte)1); using (var msg = Message.Create(AddUserFailed, writer)) { client.SendMessage(msg, SendMode.Reliable); } } } }); } catch (Exception ex) { // Return Error 2 for Database error _database.DatabaseError(client, AddUserFailed, ex); } break; } } } }
private void DarkRift_OnMessageReceived(object sender, MessageReceivedEventArgs e) { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { if (InGameClientAccountMap.ContainsKey(e.Client)) { //valid, joined player if (ServerGameManager.Instance.GameState.currentState == GameStates.GAME_IN_PROGRESS) { //game is in progress if (message.Tag == NetworkTags.Command) { ServerEntityManager.Instance.HandleCommand(reader.ReadSerializable <EntityCommand>(), InGameClientAccountMap[e.Client].PlayFabId); } else if (message.Tag == NetworkTags.Construction) { ServerEntityManager.Instance.SpawnStructure(ServerGameManager.Instance.GameState.GetPlayer(InGameClientAccountMap[e.Client].PlayFabId), reader.ReadString(), new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle())); } else if (message.Tag == NetworkTags.PlayerEvent) { ServerEntityManager.Instance.SpawnPlayerEvent(ServerGameManager.Instance.GameState.GetPlayer(InGameClientAccountMap[e.Client].PlayFabId), reader.ReadString(), new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle())); } else if (message.Tag == NetworkTags.ChatMessage) { string messageText = reader.ReadString(); using (DarkRiftWriter writer = DarkRiftWriter.Create()) { writer.Write(InGameClientAccountMap[e.Client].PlayFabId); writer.Write(messageText); using (Message response = Message.Create(NetworkTags.ChatMessage, writer)) { e.Client.SendMessage(response, SendMode.Reliable); } } } else if (message.Tag == NetworkTags.UnitList) { List <PlayerUnit> playerUnits = ServerEntityManager.Instance.GetUsablePlayerUnits(InGameClientAccountMap[e.Client].PlayFabId); if (playerUnits == null) { playerUnits = DatabaseManager.GetPlayerUnits(InGameClientAccountMap[e.Client].PlayFabId); ServerEntityManager.Instance.SetPlayerUnits(InGameClientAccountMap[e.Client].PlayFabId, playerUnits); } using (DarkRiftWriter writer = DarkRiftWriter.Create()) { foreach (PlayerUnit playerUnit in playerUnits) { writer.Write(playerUnit); } using (Message response = Message.Create(NetworkTags.UnitList, writer)) { e.Client.SendMessage(response, SendMode.Reliable); } } } else if (message.Tag == NetworkTags.SquadSelection) { List <SelectedPlayerUnit> selectedUnits = new List <SelectedPlayerUnit>(); while (reader.Position < reader.Length) { selectedUnits.Add(reader.ReadSerializable <SelectedPlayerUnit>()); } ServerEntityManager.Instance.SpawnPlayerSquad(ServerGameManager.Instance.GameState.GetPlayer(InGameClientAccountMap[e.Client].PlayFabId), selectedUnits); } } } else if (LobbyClientAccountMap.ContainsKey(e.Client)) { if (message.Tag == NetworkTags.FullUnitList) { List <PlayerUnit> playerUnits = DatabaseManager.GetPlayerUnits(LobbyClientAccountMap[e.Client].PlayFabId); using (DarkRiftWriter writer = DarkRiftWriter.Create()) { foreach (PlayerUnit playerUnit in playerUnits) { writer.Write(playerUnit); } using (Message response = Message.Create(NetworkTags.FullUnitList, writer)) { e.Client.SendMessage(response, SendMode.Reliable); } } } else if (message.Tag == NetworkTags.CustomizedUnits) { List <SelectedPlayerUnit> customizedUnits = new List <SelectedPlayerUnit>(); while (reader.Position < reader.Length) { customizedUnits.Add(reader.ReadSerializable <SelectedPlayerUnit>()); } foreach (SelectedPlayerUnit customizedUnit in customizedUnits) { DatabaseManager.SavePlayerUnit(LobbyClientAccountMap[e.Client].PlayFabId, customizedUnit); } } } if (message.Tag == NetworkTags.Connection) { //Matchmaker join request from a client, submit ticket to PlayFab string matchmakerTicket = reader.ReadString(); tempTicketMap.Add(matchmakerTicket, e.Client); ServerPlayFabManager.Instance.RedeemMatchmakerTicket(matchmakerTicket); } else if (message.Tag == NetworkTags.JoinGame) { UserJoinGame(e.Client); } } }
private void Client_MessageReceived(object sender, MessageReceivedEventArgs e) { try { using (Message message = e.GetMessage()) using (DarkRiftReader reader = message.GetReader()) { OpCodes opCode = (OpCodes)message.Tag; if (opCode != OpCodes.AuthenticationResponse && pendingConnections.Contains(e.Client.ID)) { pendingConnections.Remove(e.Client.ID); LeaveRoom(e.Client.ID); e.Client.Disconnect(); return; } switch (opCode) { case OpCodes.UpdateRoomData: string extraData = reader.ReadString(); int newMaxPlayers = reader.ReadInt32(); UpdateRoomData(e, extraData, newMaxPlayers); break; case OpCodes.AuthenticationResponse: if (reader.ReadString() == authKey) { pendingConnections.Remove(e.Client.ID); using (DarkRiftWriter writer = DarkRiftWriter.Create()) { using (Message sendAuthed = Message.Create((ushort)OpCodes.Authenticated, writer)) e.Client.SendMessage(sendAuthed, SendMode.Reliable); } } else { pendingConnections.Remove(e.Client.ID); LeaveRoom(e.Client.ID); e.Client.Disconnect(); } break; case OpCodes.RequestID: SendClientID(e); break; case OpCodes.CreateRoom: CreateRoom(e, reader.ReadInt32(), reader.ReadString(), reader.ReadBoolean(), reader.ReadString(), reader.ReadBoolean(), reader.ReadString()); break; case OpCodes.JoinServer: ushort hostID = reader.ReadUInt16(); bool useRelay = reader.ReadBoolean(); string clientLocalIP = reader.ReadString(); JoinRoom(e, hostID, useRelay, clientLocalIP); break; case OpCodes.SendData: byte[] readBuffer = readBuffers.Rent(reader.ReadInt32()); reader.ReadBytesInto(readBuffer, 0); ProcessData(e, reader, readBuffer, readBuffer.Length); break; case OpCodes.LeaveRoom: LeaveRoom(e.Client); break; case OpCodes.KickPlayer: ushort clientID = reader.ReadUInt16(); LeaveRoom(clientID, e.Client.ID); break; case OpCodes.RequestServers: SendServerList(e); break; } } } catch { // Do disconnect/kick maybe later if they do be acting up. } }