public void AddMember(Client memberToAdd) { lock (roomLock) { _members.Add(memberToAdd); } }
public void AddMemberToRoom(Client roomHost, ref Client memberToAdd) { Room room; lock (_roomListLock) { room = _roomList.FirstOrDefault(myRoom => myRoom.Host == roomHost); } if (room == null) return; // // First, remove the member from his previous room. // RemoveMemberfromRoom(memberToAdd.Room.Host, memberToAdd); // // Now add the member to the new room. // room.Members.Add(memberToAdd); memberToAdd.Room = room; // // Send a message to all the existing members in the room indicating who has joined. // MessageSender.BroadcastMessage( room.Members, PacketType.s_UserJoinedRoom, memberToAdd.UserInfo, memberToAdd); // // Now send a message to the person who has joined containing the list of room // members. // var friendList = new FriendList(); foreach (var c in room.Members) { friendList.Friends.Add(c.UserInfo); } MessageSender.SendMessage( memberToAdd, PacketType.s_RoomList, friendList); // // Now tell the joining person who the room host is. // MessageSender.SendMessage( memberToAdd, PacketType.s_HostTransfer, room.Host.UserInfo); }
internal Room(Client host) { _host = host; _members = new List<Client> {_host}; _clientsReadyForGame = new List<Client>(); roomLock = new object(); }
/// <summary> /// Sends a message to everyone on the list of the recipients, with the exception of the /// sender client, as you don't want to send a message to yourself. /// </summary> /// <param name="recipients"></param> /// <param name="packetType"></param> /// <param name="data"></param> /// <param name="sender">Client that is sending this message, set to null if this is not a /// user-initiated message</param> public static void BroadcastMessage(IEnumerable<Client> recipients, PacketType packetType, object data, Client sender) { foreach (var c in recipients) { if (c != sender) { SendMessage(c, packetType, data); } } }
public void Initialize() { // // Generate the client manager and add a number of clients to the server. // clientManager = ClientManager.GetInstance(); for (int i = 0; i < k_clientCount; i++) { var newClient = new Client(null); newClient.UserInfo.EmailAddress = "TestUser" + i.ToString(); clientManager.AddClient(newClient); } }
public void AddClient(Client client) { lock (clientListLock) { _globalClientList.Add(client); } var db = Database.GetInstance(); var user = db.GetUserByEmail(client.UserInfo.EmailAddress); if (user == null) { return; } var friend = MessageReceiver.GetFriendFromUser(user); // // Send a message saying that the user logged on to all of his friends who are online. // var friends = db.GetFriends(client.UserInfo.EmailAddress); var onlineFriends = new List<Client>(); if (friends == null) { return; } foreach (user frd in friends) { var c = GetClientFromEmailAddress(frd.email); if (null != c) { onlineFriends.Add(c); } } MessageSender.BroadcastMessage( onlineFriends, PacketType.s_UserLoggedIn, friend, client); }
/// <summary> /// TCP thread that listens for incoming connections. /// </summary> public static async void TcpListenerProcess() { Trace.WriteLine("TCP: Starting TcpListener..."); //IPAddress addr = IPAddress.Loopback; try { #if DEBUG const int port = 4032; var addr = new IPAddress(new byte[] { 192, 168, 1, 2 }); var listener = new TcpListener(addr, port); Trace.WriteLine(string.Format("TCP: Listening on {0}:{1}...", addr, port)); #else var listener = new TcpListener( RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint); listener.ExclusiveAddressUse = false; #endif listener.Start(); while (true) { var socket = await listener.AcceptSocketAsync(); var newClient = new Client(socket); newClient.OnDisconnected += OnClientDisconnected; //WorkerRole.ClientManager.GlobalClientList.Add(newClient); newClient.ReceiveAsync(); } } catch (Exception e) { Trace.WriteLine(string.Format("TCP: Caught exception!! '{0}'\n{1}", e.Message, e.StackTrace)); Trace.WriteLine("TcpListener shutting down."); } }
public void HandleMessage(ref Client client, byte[] msgBytes) { var packetBase = new PacketBase(); using (var stream = new MemoryStream(msgBytes)) { try { var reader = new BinaryReader(stream); packetBase.Read(reader); } catch (Exception e) { #if DEBUG throw; #else Trace.WriteLine(string.Format("[IncomingMessageHandler.HandleMessage] - " + "Invalid packet from client! Deserialization failed: {0}, Trace: {1}", e.Message, e.StackTrace)); #endif } } var handler = PacketHandlerFactory.GetPacketHandler(packetBase); if (handler != null) { handler.DoActions(ref client); } }
public void RemoveMember(Client memberToRemove) { lock (roomLock) { var member = _members.FirstOrDefault(m => m.UserInfo.EmailAddress == memberToRemove.UserInfo.EmailAddress); if (null != member) { _members.Remove(member); } } }
public void ChangeToRandomNewHost() { var random = new Random(); lock (roomLock) { if (_members.Count > 0) { var index = random.Next(0, _members.Count - 1); _host = _members[index]; } MessageSender.BroadcastMessage( _members, PacketType.s_HostTransfer, _host.UserInfo); } }
public void RemoveClient(Client client) { lock (clientListLock) { _globalClientList.Remove(client); } var db = Database.GetInstance(); if (client.UserInfo == null) { return; } var user = db.GetUserByEmail(client.UserInfo.EmailAddress); var friend = MessageReceiver.GetFriendFromUser(user); // // Remove the user from his room in case he is still part of one. // var roomManager = RoomManager.GetInstance(); roomManager.RemoveMemberfromRoom(client.Room.Host, client); // // Send a message saying that the user logged off to all of his friends who are online. // var friends = db.GetFriends(client.UserInfo.EmailAddress); if (null == friends) { return; } var onlineFriends = new List<Client>(); foreach (user frd in friends) { var c = GetClientFromEmailAddress(frd.email); if (null != c) { onlineFriends.Add(c); } } MessageSender.BroadcastMessage( onlineFriends, PacketType.s_UserLoggedOut, friend, client); }
public Room CreateNewRoom(Client host) { var newRoom = new Room(host); lock (_roomListLock) { _roomList.Add(newRoom); } return newRoom; }
public void ChangeHost(Client host) { lock (roomLock) { _host = host; } }
public List<Client> GetRoomMembers(Client host) { var roomMembers = new List<Client>(); lock (_roomListLock) { foreach (var room in _roomList.Where(room => room.Host == host)) { roomMembers = room.Members; break; } } return roomMembers; }
public void SignalClientIsReadyForGame(Client client) { // ToDo: Add some sort of time out guard here and drop clients if they take too long to respond. _clientsReadyForGame.Add(client); // // If this condition has been met, it means that all of the clients are ready. // if (_clientsReadyForGame.Count == _members.Count) { MessageSender.BroadcastMessage(_members, PacketType.s_GameStart, null); _clientsReadyForGame.Clear(); RoomStatus = RoomStatus.InGame; } }
/// <summary> /// Helper method that sends two messages to the user: A complete friend list, /// and then a list of friends that are online. /// </summary> /// <param name="client"></param> public static void SendOnlineAndCompleteFriendList(Client client) { // // Send the user a list of all of their friends. // var db = Database.GetInstance(); var friendList = db.GetFriends(client.UserInfo.EmailAddress); if (null != friendList) { var friendListString = CreateFriendListFromUserList(friendList); MessageSender.SendMessage( client, PacketType.s_FriendList, friendListString); // // Send the user a list of all of their friends who are online. // var onlineUsers = new List<user>(); foreach (var frd in friendList) { var clientManager = ClientManager.GetInstance(); var onlineClient = clientManager.GetClientFromEmailAddress(frd.email); if (null != onlineClient) { onlineUsers.Add(frd); } } var onlineFriends = CreateFriendListFromUserList(onlineUsers); MessageSender.SendMessage( client, PacketType.s_OnlineFriendList, onlineFriends); } }
public static void SendMessage(Client recipient, PacketType packetType, object data) { if (recipient == null) { return; } #if DEBUG // // If we're debugging, make sure that the data type matches that required by the packetType, or else throw an exception. // var type = DataPacket.PacketTypeMap[packetType]; if (type != null) { var testObject = Convert.ChangeType(data, type); } else { if (data != null) { throw new ArgumentException("Data from this packet type was expected to be null, but wasn't."); } } #endif // ToDo: Don't hardcode Packet Version 1 here. Instead, add a packet version property to Client, and switch on that. var packetBase = new PacketBase {PacketVersion = PacketVersion.Version1}; var packetV1 = new PacketV1 { PacketType = packetType, Data = data, Sender = ServerName }; packetV1.Recipients.Add(recipient.UserInfo.EmailAddress); packetBase.Data = packetV1; dynamic baseBuffer; using (var stream = new MemoryStream()) { var binaryWriter = new BinaryWriter(stream); packetBase.Write(binaryWriter); baseBuffer = stream.ToArray(); } var messageSize = baseBuffer.Length; byte[] bytes = BitConverter.GetBytes(messageSize); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } var offset = 0; var messageBuffer = new byte[sizeof(uint) + messageSize]; bytes.CopyTo(messageBuffer, offset); offset += sizeof(uint); baseBuffer.CopyTo(messageBuffer, offset); recipient.Send(messageBuffer); }
public void RemoveMemberfromRoom(Client roomHost, Client memberToRemove) { Room room; lock (_roomListLock) { room = _roomList.FirstOrDefault(myRoom => myRoom.Host == roomHost); } if (room == null) return; room.Members.Remove(memberToRemove); if (roomHost == memberToRemove) { room.ChangeToRandomNewHost(); } if (0 == room.Members.Count) { lock (_roomListLock) { _roomList.Remove(room); } } else { MessageSender.BroadcastMessage( room.Members, PacketType.s_UserLeftRoom, memberToRemove.UserInfo, memberToRemove); } }