Ejemplo n.º 1
0
        // ---------------------------------------------------------- MESSAGING
        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            txtMessage.Text = txtMessage.Text.Trim();
            if (txtMessage.Text == "")
            {
                return;
            }

            lblInfo.Text = "Sending Message...";

            dynamic     content;
            MessMessage outMessage;

            content         = new JObject();
            content.message = txtMessage.Text;

            outMessage         = new MessMessage();
            outMessage.type    = MessageTypes.TextMessage;
            outMessage.content = JsonConvert.SerializeObject(content);

            sendToServer(outMessage.toJSON());

            txtMessage.Text = "";

            lblInfo.Text = "Message sent";
        }
Ejemplo n.º 2
0
        // ---------------------------------------------------------- GUI UPDATING
        // Sends updated client list
        private void UpdateSendUserList()
        {
            MessMessage   outMessage;
            List <String> userList;

            log("Updating user list...", true);

            // Create user list from the dictionary
            userList = new List <string>();
            foreach (KeyValuePair <TcpClient, MessClient> client in clientList)
            {
                if (client.Value.isLogin)
                {
                    userList.Add(client.Value.ToString());
                }
            }

            // Generate user list message
            outMessage         = new MessMessage();
            outMessage.type    = MessageTypes.UserListUpdate;
            outMessage.content = JsonConvert.SerializeObject(userList);

            broadcast(outMessage.toJSON());
            log("Sent user list to current users");

            updateUIUserList();
            log("Current user list updated");
        }
Ejemplo n.º 3
0
        // ---------------------------------------------------------- LOG OUT
        private void logout()
        {
            string      displayMessage;
            MessMessage outMessage;

            if (clientSocket != null)
            {
                if (clientSocket.Connected)
                {
                    outMessage      = new MessMessage();
                    outMessage.type = MessageTypes.Terminate;
                    sendToServer(outMessage.toJSON());

                    messageThread.Abort();
                    clientSocket.Close();

                    displayMessage = String.Format("[{0}] You have disconnected",
                                                   DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss")
                                                   );
                    logMessage(displayMessage);
                }
            }

            reset();
        }
Ejemplo n.º 4
0
        // ---------------------------------------------------------- SOCKETS
        private void socketsInit()
        {
            clientSocket = new TcpClient();
            String serverLocation = Properties.Settings.Default.serverLocation;
            int    clientPort     = Properties.Settings.Default.clientPort;

            // Check if Server Location is empty
            if (serverLocation == "")
            {
                lblInfo.Text = "Please set Server Location in Settings Tab.";
                return;
            }
            if (clientSocket.Connected)
            {
                logInfo("Already connected to Server");
                return;
            }

            messageThread = new Thread(new ThreadStart(recieveMessagesThread));
            messageThread.IsBackground = true;
            Thread socketCreationThread = new Thread(() => {
                try {
                    // Connect socket
                    clientSocket.Connect(serverLocation, clientPort);

                    logInfo("Conneciton established! Sending handshake");
                    MessMessage outMessage = new MessMessage();
                    dynamic content        = new JObject();
                    content.token          = "MessV3".GetHashCode();

                    // Get message contents
                    outMessage.type    = MessageTypes.HandshakeData;
                    outMessage.content = JsonConvert.SerializeObject(content);

                    sendToServer(outMessage.toJSON());

                    isConnected = true;

                    messageThread.Start();
                    this.Invoke((MethodInvoker) delegate {
                        btnConnect.Text = "Disconnect";
                        tabControlMain.SelectedIndex = 1;
                    });
                }
                catch (SocketException e) {
                    logInfo("Connection error! " + e.Message);
                }
            });

            socketCreationThread.IsBackground = true;
            socketCreationThread.Start();
        }
Ejemplo n.º 5
0
        private void changeDisplayName()
        {
            MessMessage outMessage;
            dynamic     content;

            content         = new JObject();
            content.newName = txtSettingsDisplayName.Text.Trim();

            lblInfo.Text = "Attempting modification...";

            outMessage         = new MessMessage();
            outMessage.type    = MessageTypes.EditName;
            outMessage.content = JsonConvert.SerializeObject(content);

            sendToServer(outMessage.toJSON());
            lblInfo.Text = "Updated name sent";
        }
Ejemplo n.º 6
0
        private void BtnMute_Click(object sender, EventArgs e)
        {
            if (listOnlineUsers.SelectedItem == null)
            {
                setUserControlEnabled(false);
                return;
            }

            MessClient userToMute = (MessClient)listOnlineUsers.SelectedItem;
            bool       toMute     = (btnMute.Text == "Mute User");

            // Update inverse list
            updateInverseClientList();

            // Mute or unmute client
            if (toMute)
            {
                log("Muting " + userToMute.name + "...", isNew: true);
                clientList[inverseClientList[userToMute]].isMuted = true;
                btnMute.Text = "Unmute User";
            }
            else
            {
                log("Unmuting " + userToMute.name + "...", isNew: true);
                clientList[inverseClientList[userToMute]].isMuted = false;
                btnMute.Text = "Mute User";
            }

            // Creating update message
            dynamic content = new JObject();

            content.message = String.Format("{0} {1}...", userToMute.name, (toMute ? "muted" : "able to speak"));
            content.author  = "Server";

            MessMessage message = new MessMessage();

            message.type    = MessageTypes.TextMessage;
            message.time    = Utilities.DateTime2UnixTimeStamp(DateTime.UtcNow);
            message.content = JsonConvert.SerializeObject(content);

            broadcast(message.toJSON());

            UpdateSendUserList();
        }
Ejemplo n.º 7
0
        private void Register()
        {
            MessMessage outMessage;
            dynamic     details;

            details          = new JObject();
            details.name     = txtLoginDisplayName.Text;
            details.username = txtLoginUsername.Text;
            details.password = txtLoginPassword2.Text.GetHashCode();

            lblInfo.Text = "Attempting registration...";

            outMessage         = new MessMessage();
            outMessage.type    = MessageTypes.RegisterData;
            outMessage.content = JsonConvert.SerializeObject(details);

            sendToServer(outMessage.toJSON());
            lblInfo.Text = "User details sent";
        }
Ejemplo n.º 8
0
        // ---- END INITIALIZATIONS



        // ------------------------------------------------------------------------------ GENERAL FUNCTIONS
        // ---------------------------------------------------------- USER MANAGEMENT
        private void Login()
        {
            MessMessage outMessage;
            dynamic     credentials;

            credentials          = new JObject();
            credentials.type     = MessageTypes.LoginData;
            credentials.username = txtLoginUsername.Text;
            credentials.password = txtLoginPassword.Text.GetHashCode();

            lblInfo.Text = "Attempting login...";

            outMessage         = new MessMessage();
            outMessage.type    = MessageTypes.LoginData;
            outMessage.content = JsonConvert.SerializeObject(credentials);

            sendToServer(outMessage.toJSON());
            lblInfo.Text = "Credentials sent";
        }
Ejemplo n.º 9
0
        // ------------------------------------------------------------------------------ SERVER SOCKET MANAGER
        public void manageServer()
        {
            TcpClient clientSocket = default(TcpClient);

            log("Starting listen socket...", true);
            serverSocket.Start();
            log("Chat Server Started", true);
            while (true)
            {
                byte[] bytesFrom = new byte[65536];

                // Await until connection
                clientSocket = serverSocket.AcceptTcpClient();

                log("Connection attempt recieved!", true);
                try {
                    // Recieving handshake from client
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                } catch (IOException) {
                    log("Client left without handshake");
                    continue;
                }


                MessMessage inMessage, outMessage;
                string      messageRaw;
                int         token;
                dynamic     content;

                // Decoding json from bytes
                messageRaw = Encoding.Unicode.GetString(bytesFrom);

                // Deserializing json
                try {
                    inMessage = JsonConvert.DeserializeObject <MessMessage>(messageRaw);
                } catch (Exception) {
                    log("Weird message recieved:", isNew: true);
                    log(messageRaw);
                    continue;
                }

                log("Handshake!", true);
                log("From: " + clientSocket.Client.RemoteEndPoint.ToString());
                log("Packet: " + inMessage.ToString());


                Thread handshakeThread = new Thread(() => {
                    // Parse data from JSON String
                    content = JsonConvert.DeserializeObject(inMessage.content);
                    token   = content.token;

                    // TODO Ban users

                    // Validate handshake token
                    content         = new JObject();
                    content.isValid = (token == "MessV3".GetHashCode());
                    content.message = (Boolean)content.isValid ? "Valid Token" : "Invalid Token";
                    log("Token status: " + ((Boolean)content.isValid ? "valid" : "invalid"));

                    if (isServerLocked)
                    {
                        log("Server is locked! Revoking connection...");
                        content.message = "Server is locked, cannot connect.";
                        content.isValid = false;
                    }

                    // Prepare handshake response
                    outMessage         = new MessMessage();
                    outMessage.type    = MessageTypes.HandshakeData;
                    outMessage.content = JsonConvert.SerializeObject(content);
                    // Send handshake response
                    sendMessage(outMessage.toJSON(), clientSocket);

                    // If the token is valid add him to the list
                    if ((Boolean)content.isValid)
                    {
                        clientList.Add(clientSocket, new MessClient());

                        // Create and start listening thread
                        Thread clientThread       = new Thread(() => { clientThreadFunction(clientSocket); });
                        clientThread.IsBackground = true;
                        clientThread.Start();
                    }
                });
                handshakeThread.IsBackground = true;
                handshakeThread.Start();
            }
        }
Ejemplo n.º 10
0
        // ------------------------------------------------------------------------------ CLIENT THREAD FUNCTION
        public void clientThreadFunction(TcpClient socket)
        {
            int buffSize = 0;

            byte[]      inBytes;
            string      JSONMessage;
            string      authorName = "";
            int         id = 0;
            MessMessage inMessage, outMessage;

            TcpClient     clientSocket = socket;
            NetworkStream serverStream;

            try {
                // Initializing input bytes

                while (true)
                {
                    // Resetting variables
                    outMessage = new MessMessage();

                    inBytes      = new byte[65536];
                    serverStream = clientSocket.GetStream();
                    buffSize     = clientSocket.ReceiveBufferSize;

                    // Get next message from user
                    serverStream.Read(inBytes, 0, buffSize);

                    // Get data from JSON string
                    JSONMessage = Encoding.Unicode.GetString(inBytes);
                    inMessage   = JsonConvert.DeserializeObject <MessMessage>(JSONMessage);

                    dynamic content = JsonConvert.DeserializeObject(inMessage.content);
                    authorName = clientList[clientSocket].name;
                    id         = clientList[clientSocket].id;

                    // Check for message type
                    switch (inMessage.type)
                    {
                    case MessageTypes.Terminate:
                        log("User disconnecting...", true);
                        log("Info: " + clientSocket.Client.RemoteEndPoint.ToString());
                        log("Name: " + authorName);

                        clientSocket.Close();
                        log("User disconnected");
                        UpdateSendUserList();

                        content.author  = authorName;
                        content.message = "Disconnected";

                        // TODO Connection message type
                        outMessage.type    = MessageTypes.TextMessage;
                        outMessage.time    = Utilities.DateTime2UnixTimeStamp(DateTime.UtcNow);
                        outMessage.content = JsonConvert.SerializeObject(content);

                        broadcast(outMessage.toJSON());
                        return;

                    case MessageTypes.RegisterData:
                        // Create new user
                        outMessage = createUser(content);
                        sendMessage(outMessage.toJSON(), clientSocket);
                        break;

                    case MessageTypes.LoginData:
                        // Authenticate credentials
                        outMessage = validateUser(content);

                        dynamic result = JsonConvert.DeserializeObject(outMessage.content);

                        // Update client information
                        clientList[clientSocket].name    = result.name;
                        clientList[clientSocket].isLogin = result.login;
                        clientList[clientSocket].id      = result.id;

                        sendMessage(outMessage.toJSON(), clientSocket);
                        if ((Boolean)result.login)
                        {
                            UpdateSendUserList();
                        }
                        break;

                    case MessageTypes.EditName:
                        // Modify user's name
                        content.oldName = authorName;
                        content.id      = id;

                        outMessage = editUser(content);

                        content = JsonConvert.DeserializeObject(outMessage.content);

                        if ((Boolean)content.isValid)
                        {
                            clientList[clientSocket].name = content.newName;
                            UpdateSendUserList();
                        }

                        sendMessage(outMessage.toJSON(), clientSocket);
                        break;

                    case MessageTypes.TextMessage:
                        // Text message
                        if (!clientList[clientSocket].isMuted)
                        {
                            if (clientList[clientSocket].isLogin)
                            {
                                // Adding author
                                content.author = authorName;

                                // Setting message up
                                outMessage.type    = inMessage.type;
                                outMessage.time    = Utilities.DateTime2UnixTimeStamp(DateTime.UtcNow);
                                outMessage.content = JsonConvert.SerializeObject(content);

                                // Logging message
                                logMessage(outMessage);
                                // Sending message to all
                                broadcast(outMessage.toJSON());
                            }
                            else
                            {
                                // User hasn't logged in
                                content.message = "Cannot send messages, user hasn't logged in!";

                                // Setting message up
                                outMessage.type    = MessageTypes.GenericData;
                                outMessage.content = JsonConvert.SerializeObject(content);

                                // Sending message
                                sendMessage(outMessage.toJSON(), clientSocket);
                            }
                        }
                        else
                        {
                            // User is muted
                            content.message = "User is muted";

                            // Setting message up
                            outMessage.type    = MessageTypes.GenericData;
                            outMessage.content = JsonConvert.SerializeObject(content);

                            // Sending message
                            sendMessage(outMessage.toJSON(), clientSocket);
                        }
                        break;
                    }
                }
            } catch (IOException) {
                log("User disconnected forcefully", true);
                log("Info: " + clientSocket.Client.RemoteEndPoint.ToString());
                log("Name: " + authorName);

                // Remove user from client list
                clientList.Remove(clientSocket);
                clientSocket.Close();
                UpdateSendUserList();
                return;
            } catch (InvalidOperationException e) {
                // Cannot connect to database
                log(e.ToString());
                log("Cannot connect to DB!");
            } catch (Exception e) {
                // Catch ALL Exceptions just in case
                log(e.ToString());
                log("Exception raised, thread terminated...", isNew: false);
            }
        }