Reply() публичный Метод

public Reply ( byte data ) : void
data byte
Результат void
Пример #1
0
        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            /*textBox3.Invoke((MethodInvoker)delegate () {
             *   textBox3.Text += e.MessageString;
             *  e.Reply(string.Format("You said: {0}" ,  e.MessageString));
             * }
             * );*/

            //Корень сервера

            textBox3.Invoke((MethodInvoker) delegate() {
                textBox3.Text    += e.MessageString;
                string g          = e.MessageString;
                g                 = g.Substring(0, g.Length - 1);
                string gh         = "", d = "";
                DirectoryInfo dir = new DirectoryInfo(g);
                foreach (var item in dir.GetDirectories())
                {
                    gh += item.Name + " ";
                    foreach (var it in item.GetDirectories())
                    {
                        d += it.Name + "";
                    }
                }


                e.Reply(string.Format(gh + d, e.MessageString));
            }
                            );
        }
Пример #2
0
        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            int clientsConnected = server.ConnectedClientsCount;

            txtstatus.Invoke((MethodInvoker) delegate()
            {
                txtstatus.Text += string.Format("{0:HH:mm:ss tt}", DateTime.Now) + "||" + e.MessageString + Environment.NewLine;
                if (nameofuser(e.MessageString, "User:"******"User:"******"");
                    server.BroadcastLine(rpms.Replace(";", ""));
                    Thread.Sleep(100);
                    server.BroadcastLine("Cmsrv3x" + clientsConnected.ToString());
                }
                else if (commandms(e.MessageString, "cmd:online") == false)
                {
                    string rpms = e.MessageString.Replace("User:"******"");
                    server.BroadcastLine(rpms.Replace(";", ""));
                    Console.WriteLine("condition2");
                    Thread.Sleep(500);
                }
                else if (commandms(e.MessageString, "cmd:online"))
                {
                    string[] arrayname = usersList.ToArray();
                    e.Reply("Name of users in this server ");
                    Thread.Sleep(100);
                    foreach (string name in arrayname)
                    {
                        e.Reply($"Name:{name}");
                        Thread.Sleep(200);
                    }
                    e.Reply("---------------------");
                }
                else
                {
                }
            });
        }
Пример #3
0
 private void Server_DataReceived(object sender, SimpleTCP.Message e)
 {
     if (new string(e.MessageString.ToCharArray(), 0, e.MessageString.Length - 1) == "☺GetList☺")
     {
         string a = "";
         for (int k = 0; k < clients.Count; k++)
         {
             a += clients[k] + "«";
         }
         e.Reply(a);
     }
     else
     {
         if (inc == false)
         {
             outputTxt.Invoke((MethodInvoker) delegate()
             {
                 string[] message = e.MessageString.Split(split, StringSplitOptions.RemoveEmptyEntries);
                 string a         = "";
                 for (int i = 1; i < message.Length; i++)
                 {
                     a += message[i];
                 }
                 a               = new string(a.ToCharArray(), 0, a.Length - 1);
                 string msg      = "<" + clients[Convert.ToInt32(message[0])] + ">: " + a;
                 outputTxt.Text += (Environment.NewLine + msg);
                 server.BroadcastLine(Environment.NewLine + msg);
             });
         }
         else
         {
             e.Reply((i - 1) + "«");
             outputTxt.Invoke((MethodInvoker) delegate()
             {
                 clients.Add(new string(e.MessageString.ToCharArray(), 0, e.MessageString.Length - 1));
                 inc             = false;
                 string a        = new string(e.MessageString.ToCharArray(), 0, e.MessageString.Length - 1);
                 outputTxt.Text += (Environment.NewLine + a + " joined the chat.");
                 server.BroadcastLine(Environment.NewLine + a + " joined the chat.");
             });
         }
     }
 }
Пример #4
0
 private void Server_DataReceived(object sender, SimpleTCP.Message e)
 {
     listStatus.Invoke((MethodInvoker) delegate()
     {
         string text = e.MessageString;
         // text = text.Remove(text.IndexOf("!"));
         listStatus.Items.Add(text);
         //e.ReplyLine(string.Format("You said: {0}", text));
         e.Reply("You said: {0}" + text);
         //MessageBox.Show(text+" ŁIII");
     });
 }
Пример #5
0
        private void Server_DelimiterDataReceived(object sender, SimpleTCP.Message e)
        {
            try
            {
                string[] info    = e.MessageString.Split('|');
                string   message = info[0];


                switch (message)
                {
                case "go to room":
                    GoToRoom(e.TcpClient, Convert.ToInt32(info[1]), info[2]);

                    break;

                case "create room":
                    CreateRoom(e);

                    break;

                case "leave room":
                    LeaveRoom(e.TcpClient, Convert.ToInt32(info[1]));

                    break;

                case "send message":
                    SendMessage(e.TcpClient, Convert.ToInt32(info[1]), Convert.ToInt32(info[2]), info[3]);
                    break;

                case "update":
                    UpDate(e.TcpClient, Convert.ToInt32(info[1]), Convert.ToInt32(info[2]), info[3]);
                    break;

                default:
                    e.Reply("send wrong format");
                    break;
                }
            }
            catch (Exception er)
            {
            }
        }
Пример #6
0
        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            string message   = e.MessageString.Replace("\u0013", string.Empty);
            Char   delimiter = ';';

            String[] substrings = message.Split(delimiter);
            Console.WriteLine("Otrzymana wiadomość: " + message);
            if (substrings[0] == "DHCK")
            {
                DiffieHellman dh = new DiffieHellman();
                dh.CreateDeriveKey(substrings[1]);
                dh.ipAdress = ((IPEndPoint)e.TcpClient.Client.RemoteEndPoint).Address.ToString();
                clientList.Add(dh);
                e.Reply("DHSK;" + Encoding.ASCII.GetString(dh.iv) + ";" + Convert.ToBase64String(dh.serverPublicKey));
            }
            else
            {
                string encrypted_message = decryptByIP(e, message);
                //message = encrypted_message.Remove(encrypted_message.Length - 1);
                substrings = encrypted_message.Split(delimiter);
                Console.WriteLine("Odszyfrowana wiadomość " + encrypted_message);
                if (substrings[0] == "HI")
                {
                    e.Reply(sendChannelInfo());
                }
                else if (substrings[1] == "CH")
                {
                    whichChannel = Int32.Parse(substrings[2]);
                    temp_name    = substrings[0];
                    if (channelList[whichChannel].password == substrings[3])
                    {
                        e.Reply(encryptByIP(e, "PASSOK"));
                    }
                    else
                    {
                        e.Reply(encryptByIP(e, "PASSNOK"));
                    }
                }
                else if (substrings[1] == "BYE")
                {
                    Console.WriteLine("tutaj1");
                    whichChannel = Int32.Parse(substrings[2]);
                    temp_name    = substrings[0];
                    Console.WriteLine(substrings[3]);
                    Console.WriteLine("tutaj1.5");
                    channelList[whichChannel].remUser(substrings[3]);
                    buildChannelMessageInfo();
                    Console.WriteLine("tutaj2");
                    database.RemoveUserFromChannel(substrings[3]);
                    e.Reply(encryptByIP(e, "BYE"));
                }
                else if (substrings[0] == "REG")
                {
                    bool answer = database.AddUser(substrings[1], substrings[2]);
                    if (answer == true)
                    {
                        e.Reply(encryptByIP(e, "REGOK"));
                    }
                    else
                    {
                        e.Reply(encryptByIP(e, "REGNOK"));
                    }
                }
                else if (substrings[0] == "LOG")
                {
                    bool answer = database.CheckPassword(substrings[1], substrings[2]);
                    if (answer == true)
                    {
                        e.Reply(encryptByIP(e, "LOGOK"));
                    }
                    else
                    {
                        e.Reply(encryptByIP(e, "LOGNOK"));
                    }
                }
                else if (substrings[0] == "EXIT")
                {
                    removeFromDHList(e);
                }
                else
                {
                    Console.WriteLine("nieznany komunikat");
                }
            }
        }
Пример #7
0
        public static async void ParseCommand(string command, SimpleTCP.Message message, JObject json = null)
        {
            dynamic jsonResponse = new JObject();
            DBUtils utils        = new DBUtils();

            switch (command)
            {
            case "DISABLEMESSAGES":
                REASON = json["reason"].ToString();

                jsonResponse.command = "DISABLEMESSAGING";
                jsonResponse.reason  = REASON;

                string authorisedBy = json["authorisedby"].ToString();

                Util.CyanWriteLine($"{authorisedBy} has disabled message for all users.");

                messagesEnabled  = false;
                messagesDisabled = true;

                Server.server.Broadcast(jsonResponse.ToString());


                break;

            case "ENABLEMESSAGES":
                jsonResponse.command = "ENABLEMESSAGING";

                messagesDisabled = false;
                messagesEnabled  = true;

                Server.server.Broadcast(jsonResponse.ToString());

                string authoriser = json["authorisedby"].ToString();
                Util.CyanWriteLine($"{authoriser} has enabled messaging for all users.");

                break;

            case "REQUESTCHAT":

                string requesterAccountID = json["myaccountid"].ToString();
                string otherAccountID     = json["otheraccountid"].ToString();

                ClientModel requesterClient = Util.ReturnClientByID(requesterAccountID);
                ClientModel recipientClient = Util.ReturnClientByID(otherAccountID);

                EstablishedChat chat = new EstablishedChat
                {
                    PersonOneAccountID = requesterClient.UserID,
                    PersonTwoAccountID = recipientClient.UserID,
                    PersonTwoUsername  = recipientClient.Username,
                    RecipientAvatarURL = Util.GetAvatarURL(recipientClient.UserID),
                    CurrentStatus      = UserStatus.ONLINE,
                    EstablishedOn      = DateTime.UtcNow
                };

                Util.establishedChats.Add(chat);

                jsonResponse.success       = true;
                jsonResponse.recipientinfo = JsonConvert.SerializeObject(chat);

                message.Reply(jsonResponse.ToString(Formatting.None));

                break;

            case "AUTH":

                SQLiteConnection connection = utils.EstablishConnection();

                string username = json["username"].ToString();
                string password = json["password"].ToString();

                // check to see if the user is banned
                string query = $"SELECT * FROM users WHERE username='******' AND password='******'";

                SQLiteDataReader reader = utils.ExecuteReader(connection, query);

                if (reader.HasRows)
                {
                    jsonResponse.authenticated = true;
                }
                else
                {
                    jsonResponse.authenticated = false;
                    jsonResponse.reason        = "CREDENTIALS";

                    utils.CloseConnection(connection);

                    message.Reply(jsonResponse.ToString(Formatting.None));

                    return;
                }

                string UserID = "", avatarURL = "";

                while (reader.Read())
                {
                    UserID    = reader["AccountID"].ToString();
                    avatarURL = reader["avatarurl"].ToString();
                }

                reader.Close();

                string banQuery = $"SELECT * FROM bans WHERE accountid='{UserID}'";

                SQLiteDataReader banReader = utils.ExecuteReader(connection, banQuery);

                if (banReader.HasRows)
                {
                    // user is banned
                    jsonResponse.authenticated = false;
                    jsonResponse.reason        = "BANNED";
                }
                else
                {
                    jsonResponse.accountID = UserID;
                    jsonResponse.avatarURL = avatarURL;
                    if (messagesDisabled)
                    {
                        jsonResponse.information = "MESSAGINGDISABLED";
                        jsonResponse.reason      = REASON;
                    }
                    else
                    {
                        jsonResponse.information = "MESSAGINGENABLED";
                    }
                }

                while (banReader.Read())
                {
                    jsonResponse.BanID      = banReader["id"].ToString();
                    jsonResponse.AccountID  = banReader["accountid"].ToString();
                    jsonResponse.Reason     = banReader["reason"].ToString();
                    jsonResponse.expires    = banReader["expires"].ToString();
                    jsonResponse.Appealable = banReader["appealable"].ToString();
                }

                utils.CloseConnection(connection);

                message.Reply(jsonResponse.ToString(Formatting.None));

                int port = int.Parse(message.TcpClient.Client.RemoteEndPoint.ToString().Split(':')[1]);

                Int64 userID;

                if (UserID.Equals(""))
                {
                    userID = 0;
                }
                else
                {
                    userID = int.Parse(UserID);
                }

                Util.AddUserOnline(message.TcpClient, json["username"].ToString(), json["IP"].ToString(), port, userID);

                break;

            case "REGISTER":

                string usrName    = json["username"].ToString();
                string pwd        = json["password"].ToString();
                string IPAddress  = json["IP"].ToString();
                string avatarURLl = json["avatarURL"].ToString();

                long AccountID = Util.GenerateAccountID();

                SQLiteConnection sQLiteConnection = utils.EstablishConnection();

                int rowsAffected = await utils.ExecuteNonQuery(sQLiteConnection, $"INSERT INTO users (AccountID, username, password, avatarurl, lastip) VALUES ('{AccountID}', '{usrName}', '{pwd}', '{avatarURLl}', '{IPAddress}')");


                if (rowsAffected == 1)
                {
                    jsonResponse.success   = true;
                    jsonResponse.AccountID = AccountID;
                    jsonResponse.username  = usrName;
                    jsonResponse.avatarURL = avatarURLl;

                    utils.CloseConnection(sQLiteConnection);

                    message.Reply(jsonResponse.ToString(Formatting.None));
                }
                else
                {
                    jsonResponse.success = false;

                    utils.CloseConnection(sQLiteConnection);

                    message.Reply(jsonResponse.ToString(Formatting.None));
                }

                break;

            case "VERIFYUSERNAME":

                string usernameToCheck = json["username"].ToString();

                SQLiteConnection conn = utils.EstablishConnection();

                SQLiteDataReader dataReader = utils.ExecuteReader(conn, $"SELECT * FROM users WHERE username='******'");

                if (dataReader.HasRows)
                {
                    jsonResponse.exists = true;
                }
                else
                {
                    jsonResponse.exists = false;
                }

                dataReader.Close();

                utils.CloseConnection(conn);

                message.Reply(jsonResponse.ToString(Formatting.None));

                break;

            case "DISCONNECT":

                Util.RemoveUserOnline(Util.ReturnClientModel(message.TcpClient));

                break;

            case "REPORT":

                UserReport report = new UserReport();

                report.ReporterAccountID = long.Parse(json["reporterid"].ToString());
                report.ReportedAccountID = long.Parse(json["reportedid"].ToString());
                report.ReportID          = Util.GenerateAccountID();

                string categoryText = json["category"].ToString();

                switch (categoryText)
                {
                case "RACISM":
                    report.ReportCategory = ReportCategory.RACIST;
                    break;

                case "OFFENSIVE":
                    report.ReportCategory = ReportCategory.OFFENSIVE;
                    break;

                case "SPAM":
                    report.ReportCategory = ReportCategory.SPAM;
                    break;

                case "COMPROMISEDACCOUNT":
                    report.ReportCategory = ReportCategory.ACCOUNTHACKED;
                    break;

                case "DOX":
                    report.ReportCategory = ReportCategory.PERSONALINFORMATION;
                    break;

                default:
                    report.ReportCategory = ReportCategory.OTHER;
                    break;
                }

                report.Timestamp  = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                report.ChatLogURL = Util.CreateChatLog(json, report);

                if (await Util.CreateReport(report))
                {
                    // report made successfully
                    jsonResponse.success = true;
                }
                else
                {
                    // failed to create report
                    jsonResponse.success = false;
                }

                message.Reply(jsonResponse.ToString(Formatting.None));

                break;
            }
        }
Пример #8
0
        private void Server_DelimiterDataReceived(object sender, SimpleTCP.Message e)
        {
            if (string.IsNullOrWhiteSpace(e.MessageString))
            {
                AppendMessage("Empty message received.");
                return;
            }

            string message = e.MessageString.Trim();

            if (!message.Contains('?'))
            {
                AppendMessage($"Message does not appear to have a query in it: '{message}'.");
                return;
            }

            message = message.Substring(message.IndexOf('?'));

            string reply = null;
            var    dif   = DateTime.Now - start;

            switch (message)
            {
            case "?Q100":
                AppendMessage("?Q100 - Machine Serial Number.");
                reply = $"SERIAL NUMBER, 1234567";
                break;

            case "?Q101":
                AppendMessage("?Q101 - Control Software Version.");
                reply = $"SOFTWARE VERSION, 100.17.000.2037";
                break;

            case "?Q102":
                AppendMessage("?Q102 - Machine Model Number.");
                reply = $"MODEL, CSMD-G2";
                break;

            case "?Q104":
                AppendMessage("?Q104 - Mode (LIST PROG, MDI, etc.).");
                reply = $"MODE, ZERO";
                break;

            case "?Q200":
                AppendMessage("?Q200 - Tool Changes (total).");
                reply = $"TOOL CHANGES, {toolChanges}";
                break;

            case "?Q201":
                AppendMessage("?Q201 - Tool Number in use.");
                reply = $"USING TOOL, {txtTool.Value}";
                break;

            case "?Q300":
                AppendMessage("?Q300 - Power-on Time (total).");
                reply = $"P.O. TIME, {dif.TotalHours:00000}:{dif.Minutes}:{dif.Seconds}";
                break;

            case "?Q301":
                AppendMessage("?Q301 - Motion Time (total).");
                reply = $"C.S. TIME, {dif.TotalHours:00000}:{dif.Minutes}:{dif.Seconds}";
                break;

            case "?Q303":
                AppendMessage("?Q303 - Last Cycle Time.");
                reply = $"LAST CYCLE, 00000:00:13";
                break;

            case "?Q304":
                AppendMessage("?Q304 - Previous Cycle Time.");
                reply = $"PREV CYCLE, 00000:00:01";
                break;

            case "?Q402":
                AppendMessage("?Q402 - M30 Parts Counter #1 (resettable at control).");
                reply = $"M30 #1, 380";
                break;

            case "?Q403":
                AppendMessage("?Q403 - M30 Parts Counter #2 (resettable at control).");
                reply = $"M30 #2, 380";
                break;

            case "?Q500":
                AppendMessage("?Q500 - Three-in-one (PROGRAM, Oxxxxx, STATUS, PARTS, xxxxx.");
                reply = $"PROGRAM, MDI, IDLE, PARTS, 380";
                break;

            default:
                AppendMessage($"Unknown message: '{message}'");
                break;
            }

            e.Reply($"{reply}\r\n");
            AppendMessage(reply);
        }