示例#1
0
        public void JoinRoomHandler(ChatExchange chatExchange, User user)
        {
            ChatRoom requestedRoom    = GetRoom(chatExchange.ExchangeTargetName);
            string   responseExchange = String.Empty;

            if (!requestedRoom.RequiresPassword)
            {
                requestedRoom.AddUser(user);
                responseExchange = "JOINED";
            }
            else
            {
                if (chatExchange.Exchange == requestedRoom.Password)
                {
                    requestedRoom.AddUser(user);
                    responseExchange = "JOINED";
                }
                else
                {
                    responseExchange = "INVALIDPASSWORD";
                }
            }
            string encoded = ChatExchange.Encode("", ChatExchangeType.Command, ChatExchangeTarget.Individual, "Server", "", responseExchange);

            byte[] sendBuffer = Encoding.UTF8.GetBytes(encoded);
            user.Connection.Connection.Send(sendBuffer);
        }
示例#2
0
        public void LeaveRoomHandler(ChatExchange chatExchange, User user)
        {
            user.LeaveRoom();
            string encoded = ChatExchange.Encode("", ChatExchangeType.Command, ChatExchangeTarget.Individual, "Server", "", "LEFT");

            byte[] sendBuffer = Encoding.UTF8.GetBytes(encoded);
            user.Connection.Connection.Send(sendBuffer);
        }
示例#3
0
        public void SendCommand(string command)
        {
            ChatExchange exchange = new ChatExchange()
            {
                LoginToken = LoginToken, ExchangeType = ChatExchangeType.Command, ExchangeTargetName = "", SenderName = "", ExchangeTarget = ChatExchangeTarget.Server, Exchange = command
            };

            socket.Send(exchange);
            expectingCommandResponse = true;
        }
示例#4
0
        public AvailableRoom[] GetAvailableRooms()
        {
            socket.Send(Encoding.UTF8.GetBytes(ChatExchange.Encode(LoginToken, ChatExchangeType.ChatRoomList, ChatExchangeTarget.Server, "", "", "")));
            byte[]               receiveBuffer = new byte[1024 * 8];
            int                  receiveSize   = socket.Receive(receiveBuffer);
            RoomListExchange     exchange      = RoomListExchange.Decode(receiveBuffer, receiveSize);
            List <AvailableRoom> rooms         = exchange.Rooms;

            return(rooms.ToArray());
        }
示例#5
0
        public void CommandHandler(ChatExchange chatExchange, User user)
        {
            string command = chatExchange.Exchange;

            string[] parts = command.Split(' ');
            switch (parts[0].ToLower())
            {
            case "help":
                string helpMessage = string.Format("Available Commands:{0}> '/help' - Display a list of commands.{0}> /poke <user> [message] - Poke a user with a message.", Environment.NewLine);
                user.Connection.Connection.Send(new CommandExchangeResponse()
                {
                    ResponseType = CommandResponse.Success, OutputMessage = helpMessage, FurtherInfo = "Displays a list of commands."
                }.EncodeBytes());
                break;

            case "poke":
                string          response     = string.Empty;
                CommandResponse responseType = CommandResponse.Fail;
                if (command.Length > "poke".Length)
                {
                    string username   = parts[1];
                    User   targetUser = userHandler.GetUserByName(username);
                    if (targetUser != null)
                    {
                        targetUser.Connection.Connection.Send(new ChatExchange()
                        {
                            SenderName = user.Name, ExchangeTarget = ChatExchangeTarget.Individual, ExchangeType = ChatExchangeType.Command, ExchangeTargetName = "poke", Exchange = parts.Length >= 3 ? string.Format("{0}: {1}", user.Name, command.Substring((parts[0] + parts[1]).Length + 1, command.Length - (parts[0] + parts[1]).Length - 1)) : "You were poked."
                        });
                        responseType = CommandResponse.Success;
                        response     = string.Format("Poked '{0}'...", username);
                    }
                    else
                    {
                        response = string.Format("Could not find user '{0}'...", username);
                    }
                }
                else
                {
                    response = "Target user required. > /poke <user> [message]";
                }
                user.Connection.Connection.Send(new CommandExchangeResponse()
                {
                    ResponseType = responseType, OutputMessage = response, FurtherInfo = "Pokes a user."
                }.EncodeBytes());
                break;

            default:
                user.Connection.Connection.Send(new CommandExchangeResponse()
                {
                    ResponseType = CommandResponse.UnknownCommand, OutputMessage = "Unknown command.", FurtherInfo = "Command not found."
                }.EncodeBytes());
                break;
            }
        }
示例#6
0
        public JoinRoomOutcome CreateRoom(string roomName, string roomPassword)
        {
            socket.Send(Encoding.UTF8.GetBytes(ChatExchange.Encode(LoginToken, ChatExchangeType.CreateRoom, ChatExchangeTarget.Server, "", roomName, roomPassword)));
            byte[]       receiveBuffer = new byte[1024 * 2];
            int          receiveSize   = socket.Receive(receiveBuffer);
            ChatExchange exchange      = ChatExchange.Decode(receiveBuffer, receiveSize);

            if (exchange.Exchange == "JOINED")
            {
                return(JoinRoomOutcome.Success);
            }
            return(JoinRoomOutcome.Fail);
        }
示例#7
0
        public void ChatRoomListHandler(ChatExchange chatExchange, User user)
        {
            RemoveEmptyTempRooms();
            List <AvailableRoom> availableRooms = new List <AvailableRoom>();

            foreach (ChatRoom room in chatRooms)
            {
                availableRooms.Add(room.GetAvailableRoom());
            }
            string encoded = RoomListExchange.Encode(availableRooms);

            byte[] sendBuffer = Encoding.UTF8.GetBytes(encoded);
            user.Connection.Connection.Send(sendBuffer);
        }
示例#8
0
        public void OnCommandReceive(ChatExchange exchange)
        {
            switch (exchange.ExchangeTargetName)
            {
            case "poke":
                if (pokeEnabled)
                {
                    chatPage.OutputTextSafe(string.Format("Poked by '{0}'...", exchange.SenderName));
                    new Thread(new ThreadStart(delegate { MessageBox.Show(exchange.Exchange, "You have been poked!"); })).Start();
                }
                break;

            default:
                break;
            }
        }
示例#9
0
        public void Message(ChatExchange exchange)
        {
            string userName = string.Empty;

            foreach (User user in Users)
            {
                if (user.Token == exchange.LoginToken)
                {
                    exchange.SenderName = string.Format("{0}{1}", user.IsAdmin ? "<Admin> " : "", user.IsRoomHost ? string.Format("<Host> [{0}]", user.Name) : string.Format("[{0}]", user.Name));
                    foreach (User currentUser in Users)
                    {
                        currentUser.Message(exchange);
                    }
                }
            }
        }
示例#10
0
        public void MessageHandler(ChatExchange chatExchange, User user)
        {
            switch (chatExchange.ExchangeTarget)
            {
            case ChatExchangeTarget.ChatRoom:
                user.CurrentChatRoom.Message(chatExchange);
                break;

            case ChatExchangeTarget.Individual:
                break;

            case ChatExchangeTarget.Server:
            default:
                break;
            }
        }
示例#11
0
        public JoinRoomOutcome JoinRoom(string roomId, string password = "")
        {
            socket.Send(Encoding.UTF8.GetBytes(ChatExchange.Encode(LoginToken, ChatExchangeType.JoinRoom, ChatExchangeTarget.Server, "", roomId, password)));
            byte[]       receiveBuffer = new byte[1024 * 2];
            int          receiveSize   = socket.Receive(receiveBuffer);
            ChatExchange exchange      = ChatExchange.Decode(receiveBuffer, receiveSize);

            if (exchange.Exchange == "JOINED")
            {
                return(JoinRoomOutcome.Success);
            }
            if (exchange.Exchange == "INVALIDPASSWORD")
            {
                return(JoinRoomOutcome.InvalidPassword);
            }
            return(JoinRoomOutcome.Fail);
        }
示例#12
0
        public void CreateChatRoomHandler(ChatExchange chatExchange, User user)
        {
            string roomName     = chatExchange.ExchangeTargetName;
            string roomPassword = chatExchange.Exchange;

            ChatRoom newRoom = new ChatRoom {
                ID = GetRoomId(), MaxUsers = 10, Name = roomName, Password = roomPassword, TempRoom = true
            };

            chatRooms.Add(newRoom);

            newRoom.AddUser(user);
            user.IsRoomHost = true;

            string encoded = ChatExchange.Encode("", ChatExchangeType.Command, ChatExchangeTarget.Individual, "Server", newRoom.ID, "JOINED");

            byte[] sendBuffer = Encoding.UTF8.GetBytes(encoded);
            user.Connection.Connection.Send(sendBuffer);
        }
示例#13
0
        public void StartListen(Action <ChatExchange> receiveCommand, Action <ChatExchange> commandCommand, Action <Exception> ExceptionAction = null)
        {
            try
            {
                bool doReceive = true;
                while (doReceive)
                {
                    byte[] receiveBuffer = new byte[1024 * 2];
                    int    receiveSize   = socket.Receive(receiveBuffer);
                    if (expectingCommandResponse)
                    {
                        CommandResponseHandler(CommandExchangeResponse.Decode(receiveBuffer, receiveSize)); expectingCommandResponse = false;
                    }
                    else
                    {
                        ChatExchange chatExchange = ChatExchange.Decode(receiveBuffer, receiveSize);
                        switch (chatExchange.ExchangeType)
                        {
                        case ChatExchangeType.Message:
                            receiveCommand?.Invoke(chatExchange);
                            break;

                        case ChatExchangeType.Command:
                            if (chatExchange.Exchange == "LEFT")
                            {
                                doReceive = false;
                            }
                            commandCommand?.Invoke(chatExchange);
                            continue;

                        default:
                            break;
                        }
                    }
                }
            }
            catch (SocketException e)
            {
                ExceptionAction?.Invoke(e);
            }
        }
示例#14
0
 public void Message(ChatExchange exchange)
 {
     Connection.Connection.Send(Encoding.UTF8.GetBytes(exchange.Encode()));
 }
示例#15
0
 public bool Verify(ChatExchange chatExchange)
 {
     return(Token == chatExchange.LoginToken);
 }
示例#16
0
 public void SendToAll(string message)
 {
     ChatExchange e = new ChatExchange {
         Exchange = message, ExchangeTarget = ChatExchangeTarget.Server,
     };
 }
示例#17
0
 public void LeaveRoom()
 {
     socket.Send(Encoding.UTF8.GetBytes(ChatExchange.Encode(LoginToken, ChatExchangeType.LeaveRoom, ChatExchangeTarget.Server, "", "", "")));
 }
示例#18
0
 public void SendMessage(string message)
 {
     socket.Send(Encoding.UTF8.GetBytes(ChatExchange.Encode(LoginToken, ChatExchangeType.Message, ChatExchangeTarget.ChatRoom, "", "", message)));
 }
示例#19
0
        private void ClientHandler(int id)
        {
            while (true)
            {
                ClientConnection currentClient = clientConnections[id] = new ClientConnection(id, socket.Accept());
                try
                {
                    Console.WriteLine("{0} <{1}> - Received connection from {2}", ChatTime.GetTimeFormat(), currentClient.ID, currentClient.GetConnectionString());
                    byte[]        receiveBuffer = new byte[1024 * 2];
                    int           receiveSize   = currentClient.Connection.Receive(receiveBuffer);
                    LoginExchange loginExchange = LoginExchange.Decode(receiveBuffer, receiveSize);
                    Console.WriteLine("{0} <{1}> - Login request from '{2}'.", ChatTime.GetTimeFormat(), currentClient.ID, loginExchange.Username);
                    LoginExchangeResponse loginExchangeResponse = userHandler.HandleLoginExchange(loginExchange, currentClient);

                    string loginResponseData = loginExchangeResponse.Encode();
                    byte[] loginResponse     = Encoding.UTF8.GetBytes(loginResponseData);
                    currentClient.Connection.Send(loginResponse);

                    if (loginExchangeResponse.ExchangeType == LoginExchangeResponseCode.Successful)
                    {
                        User user = userHandler.GetUser(id);
                        Console.WriteLine("{0} <{1}> - User '{2}' logged in with token '{3}'.", ChatTime.GetTimeFormat(), currentClient.ID, user.Name, user.Token);
                        while (user != null)
                        {
                            receiveBuffer = new byte[1024 * 2];
                            receiveSize   = currentClient.Connection.Receive(receiveBuffer);
                            if (receiveSize > 0)
                            {
                                ChatExchange chatExchange = ChatExchange.Decode(Encoding.UTF8.GetString(receiveBuffer, 0, receiveSize));
                                if (user.Verify(chatExchange))
                                {
                                    switch (chatExchange.ExchangeType)
                                    {
                                    case ChatExchangeType.Message:
                                        Console.WriteLine("{0} <{1}> - [{2}] {3}: {4}", ChatTime.GetTimeFormat(), currentClient.ID, user.CurrentChatRoom.Name, user.Name, chatExchange.Exchange);
                                        MessageHandler(chatExchange, user);
                                        break;

                                    case ChatExchangeType.Command:
                                        Console.WriteLine("{0} <{1}> - Command: {2}", ChatTime.GetTimeFormat(), currentClient.ID, chatExchange.Exchange);
                                        CommandHandler(chatExchange, user);
                                        break;

                                    case ChatExchangeType.ChatRoomList:
                                        Console.WriteLine("{0} <{1}> - Requested Chat Room List", ChatTime.GetTimeFormat(), currentClient.ID);
                                        ChatRoomListHandler(chatExchange, user);
                                        break;

                                    case ChatExchangeType.JoinRoom:
                                        Console.WriteLine("{0} <{1}> - Join Room: ID '{2}'", ChatTime.GetTimeFormat(), currentClient.ID, chatExchange.ExchangeTargetName);
                                        JoinRoomHandler(chatExchange, user);
                                        break;

                                    case ChatExchangeType.LeaveRoom:
                                        Console.WriteLine("{0} <{1}> - Leave Room", ChatTime.GetTimeFormat(), currentClient.ID);
                                        LeaveRoomHandler(chatExchange, user);
                                        break;

                                    case ChatExchangeType.CreateRoom:
                                        Console.WriteLine("{0} <{1}> - Create Room: '{2}'", ChatTime.GetTimeFormat(), currentClient.ID, chatExchange.ExchangeTargetName);
                                        CreateChatRoomHandler(chatExchange, user);
                                        break;

                                    case ChatExchangeType.Error:
                                        Console.WriteLine("{0} <{1}> - ChatExchange Error Occurred", ChatTime.GetTimeFormat(), currentClient.ID, chatExchange.ExchangeTargetName);
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    Console.WriteLine("{0} <{1}> - Ending connection.", ChatTime.GetTimeFormat(), currentClient.ID);
                }
                catch (SocketException)
                {
                    Console.WriteLine("{0} <{1}> - Lost connection.", ChatTime.GetTimeFormat(), currentClient.ID);
                }
                finally
                {
                    userHandler.Logout(id);
                    currentClient = null;
                }
            }
        }