예제 #1
0
 private void ok_Click(object sender, EventArgs e)
 {
     //если пользователь ввел не все данные (логин, пароль, адрес сервера)
     //то напомни ему чтобы ввел
     if (name.Text.Length == 0 || pas1.Text.Length == 0 || ipp.Text.Length == 0)
     {
         MessageBox.Show("Введите значения во все поля!", "Ошибка",
                         MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else
     {
         try
         {
             //парсинг введенных пользователем данных
             string login = name.Text;
             string pas   = pas1.Text;
             string ip    = ipp.Text.Split(':')[0];
             int    port  = Convert.ToInt32(ipp.Text.Split(':')[1]);
             //создание объекта для общения с сервером, подключение к нему
             Client2Server C2S = new Client2Server(login, pas, ip, port);
             //отсылание серверу пустого сообщения для проверки связи
             C2S.SendMessage(Client2Server.ClientKeys.NULL, "");
             //если все прошло успешно открывай форму с чатом
             _4at ch = new _4at(C2S);
             ch.Show(this);
             this.Hide();
         }
         catch
         {
             //если не получилось то либо сервер не поднят, либо юзер ошибся с данными
             MessageBox.Show("Ошибка подключения к серверу\nОшибка адреса сервера или " +
                             "сервер отсутсвует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
예제 #2
0
 static void FileRead(FileStream fs, Client2Server C2S)
 {
     byte[] buf = new byte[1400];
     while (fs.Read(buf, 0, 1400) > 0)
     {
         C2S.SendMessage(Client2Server.ClientKeys.FILE, Encoding.UTF8.GetString(buf));
     }
     fs.Close();
     C2S.SendMessage(Client2Server.ClientKeys.FILEREADY, "");
 }
예제 #3
0
        public _4at(Client2Server server)
        {
            InitializeComponent();
            C2S = server;
            C2S.SendMessage(Client2Server.ClientKeys.AUTORISATION, server.userName + ";" + server.userPas);
            timer1.Enabled = true;
            openFileDialog1.AddExtension = true;
            ManagementObjectSearcher   searcher   = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
            ManagementObjectCollection collection = searcher.Get();

            WinUser = ((string)collection.Cast <ManagementBaseObject>().First()["UserName"]).Split('\\')[1];
        }
예제 #4
0
 private async void ok_Click(object sender, EventArgs e)
 {
     //обработка ошибок пользователя, в том числе проверка политики длинны пароля
     if (name.Text.Length == 0 || pas1.Text.Length == 0 || pas2.Text.Length == 0 || ipp.Text.Length == 0)
     {
         MessageBox.Show("Введите значения во все поля!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else if (pas1.Text != pas2.Text)
     {
         MessageBox.Show("Пароли не совпадают", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else if (pas1.Text.Length < 6)
     {
         MessageBox.Show("Пароль слишком короткий", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     else
     {
         try
         {
             //временное подключение к серверу
             C2S = new Client2Server(ipp.Text.Split(':')[0], Convert.ToInt32(ipp.Text.Split(':')[1]));
             //отправка на сервер никнейма и пароля
             C2S.SendReg(name.Text, pas1.Text);
             int i = 0;
             //ожидание ответа от сервера
             (string, string)s = ("", "");
             while (i < 100 && s.Item1 != Client2Server.GetDescription(Client2Server.ServerKeys.REJECT))
             {
                 i++;
                 s = await C2S.GetMessageAsync();
             }
             //отключение от сервера
             C2S.Disconnect();
             //если сервер отправил сообщение об отклонении регистрации (такой ник уже существует)
             //то сообщи об этом юзеру
             if (s.Item1 == Client2Server.GetDescription(Client2Server.ServerKeys.REJECT))
             {
                 MessageBox.Show("Ошибка регистрации", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             //иначе пользователь зарегестрирован
             else
             {
                 this.Close();
             }
         }
         catch
         {
             MessageBox.Show("Ошибка подключения к серверу\nОшибка адреса сервера или сервер отсутсвует",
                             "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
예제 #5
0
        private async void timer1_Tick(object sender, EventArgs e)
        {
            var s = await C2S.GetMessageAsync();

            if (s.Item1 == ((int)Client2Server.ServerKeys.USERLIST).ToString())  //get userList
            {
                string[] users = s.Item2.Split(';');
                foreach (string x in users)
                {
                    userList.Items.Add(x);
                }
                chk2 = true;
            }
            else if (s.Item1 == ((int)Client2Server.ServerKeys.USERADD).ToString()) //get new user
            {
                userList.Items.Add(s.Item2);
                chatSpace.AppendText(s.Item2, Color.Green);
                chatSpace.AppendText(" присоединился к чату", Color.Green);
                chatSpace.AppendText(Environment.NewLine);
            }
            else if (s.Item1 == ((int)Client2Server.ServerKeys.USERREMOVE).ToString()) //remowe disconnected user
            {
                userList.Items.Remove(s.Item2);
                chatSpace.AppendText(s.Item2, Color.DarkRed);
                chatSpace.AppendText(" покинул чат", Color.DarkRed);
                chatSpace.AppendText(Environment.NewLine);
            }
            else if (s.Item1 == ((int)Client2Server.ServerKeys.PRIVATE).ToString()) //private message
            {
                chatSpace.AppendText("Шепот от " + s.Item2, Color.HotPink);
                chatSpace.AppendText(Environment.NewLine);
            }
            else if (s.Item1 == ((int)Client2Server.ServerKeys.BROADCAST).ToString())
            {
                string[] ss  = s.Item2.Split(':');
                string   sss = "";
                for (int i = 1; i < ss.Length; i++)
                {
                    sss += ss[i];
                }
                chatSpace.AppendText(ss[0].ToString(), Color.Blue);
                chatSpace.AppendText(": " + sss);
                chatSpace.AppendText(Environment.NewLine);
            }
            else if (s.Item1 == Client2Server.GetDescription(Client2Server.ServerKeys.FILEINFO))
            {
                DialogResult result = MessageBox.Show("Пользователь " + s.Item2.Split(':')[0] + " хочет отправить Вам файл "
                                                      + s.Item2.Split(':')[1] + " размером " + NotByteLength(s.Item2.Split(':')[2]) + "\nПринять его?", "Извещение о файле",
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (result == DialogResult.Yes)
                {
                    filePathSave = s.Item2.Split(':')[1];
                    chatSpace.AppendText("Прием файла от " + s.Item2.Split(':')[0] + ": " + s.Item2.Split(':')[1], Color.DarkViolet);
                    chatSpace.AppendText(Environment.NewLine);
                    C2S.SendMessage(Client2Server.ClientKeys.FILEACCEPT, s.Item2.Split(':')[0]);
                }
                if (result == DialogResult.No)
                {
                    C2S.SendMessage(Client2Server.ClientKeys.FILEREMOVE, s.Item2.Split(':')[0]);
                }
            }
            else if (s.Item1 == Client2Server.GetDescription(Client2Server.ServerKeys.FILE))
            {
                string     filename = @"C:\Users\" + WinUser + @"\Downloads\" + filePathSave;
                FileStream fs       = new FileStream(filename, FileMode.OpenOrCreate);
                byte[]     data     = Encoding.UTF8.GetBytes(s.Item2.Remove(0, 1));
                fs.Seek(0, SeekOrigin.End);
                fs.Write(data, 0, data.Length);
                fs.Close();
            }
            else if (s.Item1 == Client2Server.GetDescription(Client2Server.ServerKeys.FILEACCEPT))
            {
                chatSpace.AppendText("Пользователь принял файл", Color.DarkViolet);
                FileStream fs = new FileInfo(filePathSend).Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                await Task.Factory.StartNew(() => FileRead(fs, C2S));

                //FileRead(fs, C2S);
                chatSpace.AppendText(Environment.NewLine);
            }

            else if (s.Item1 == Client2Server.GetDescription(Client2Server.ServerKeys.FILEREMOVE))
            {
                chatSpace.AppendText("Пользователь отклонил файл", Color.DarkViolet);
                chatSpace.AppendText(Environment.NewLine);
            }
            else if (s.Item1 == Client2Server.GetDescription(Client2Server.ServerKeys.FILEREADY))
            {
                chatSpace.AppendText("Файл сохранен", Color.DarkViolet);
                chatSpace.AppendText(Environment.NewLine);
            }
            else if (s.Item1 == "" && chk)
            {
                chatSpace.AppendText(s.Item2);
                chatSpace.AppendText(Environment.NewLine);
                chk = false;
                timer1.Stop();
                timer2.Start();
                userList.Items.Clear();
            }
        }