Esempio n. 1
0
        private void button6_Click(object sender, EventArgs e)//参数发送
        {
            char[]      a  = new char[8];
            RemoteDebug rd = new RemoteDebug();

            if (!rd.flag11)
            {
                a[0] = '0';
            }
            if (rd.flag11)
            {
                a[0] = '1';
            }

            if (!rd.flag22)
            {
                a[1] = '0';
            }
            if (rd.flag22)
            {
                a[1] = '1';
            }

            if (!rd.flag33)
            {
                a[2] = '0';
            }
            if (rd.flag33)
            {
                a[2] = '1';
            }

            if (!rd.flag44)
            {
                a[3] = '0';
            }
            if (rd.flag44)
            {
                a[3] = '1';
            }

            if (!rd.flag55)
            {
                a[4] = '0';
            }
            if (rd.flag55)
            {
                a[4] = '1';
            }

            if (!rd.flag66)
            {
                a[5] = '0';
            }
            if (rd.flag66)
            {
                a[5] = '1';
            }

            if (!rd.flag77)
            {
                a[6] = '0';
            }
            if (rd.flag77)
            {
                a[6] = '1';
            }

            if (!rd.flag88)
            {
                a[7] = '0';
            }
            if (rd.flag88)
            {
                a[7] = '1';
            }
            //string SendData = new string(a);
            //MessageBox.Show(SendData);
            string SendData = textBox5.Text;

            if (SendData != "")
            {
                bool flag = true;
                for (int i = 0; i < SendData.Length; i++)
                {
                    int num = SendData[i] - '0';
                    if (num != 0 && num != 1)
                    {
                        flag = false;
                        break;
                    }
                }
                if (!flag || SendData.Length != 8)
                {
                    MessageBox.Show("请输入8位二进制数!");
                    return;
                }
            }
            //调试记录存入数据库
            string          constr = "Server=127.0.0.1;Database=tonghua;User Id=root;Password=5120154230;";
            MySqlConnection mycon  = new MySqlConnection(constr);

            mycon.Open();//打开连接
            byte[] arrMsg  = Encoding.UTF8.GetBytes(SendData);
            byte[] SendMsg = new byte[arrMsg.Length + 1];
            SendMsg[0] = 6;
            Buffer.BlockCopy(arrMsg, 0, SendMsg, 1, arrMsg.Length);
            List <string> test = new List <string>(ClientInformation.Keys);

            for (int i = 0; i < ClientInformation.Count; i++)
            {
                Socket socket = ClientInformation[test[i]];
                socket.Send(SendMsg);
                textBox5.Clear();
                IPAddress ClientIP = (socket.RemoteEndPoint as IPEndPoint).Address;
                source      = ServerSocket.LocalEndPoint.ToString();
                destination = ClientIP.ToString();
                string debug_data = SendData;
                old_data = Information;
                string record = "insert into debug_data (source,destination,datetime,old_data,debug_data) " +
                                "values('" + source + "','" + destination + "','" + DateTime.Now + "','" + old_data + "','" + debug_data + "')";
                MySqlCommand cmd = new MySqlCommand(record, mycon); //创建执行
                cmd.ExecuteNonQuery();                              //执行SQL
                mycon.Close();
                mycon.Dispose();
            }
        }
Esempio n. 2
0
        private void ReceiveMessage(Object SocketClient)///接收消息
        {
            Socket ReceiveSocket = (Socket)SocketClient;
            long   FileLength    = 0;
            long   PictureLength = 0;

            byte[] buffer = new byte[1024];
            //Screen_Show screen_Show = new Screen_Show();
            while (this.Visible)
            {
                string          constr = "Server=127.0.0.1;Database=tonghua;User Id=root;Password=5120154230;";
                MySqlConnection mycon  = new MySqlConnection(constr);
                mycon.Open();//打开连接
                int    ReceiveLength = 0;
                byte[] result        = new byte[1024 * 1024 * 10];
                try
                {
                    /*将IPAdress转换为int*/
                    //string addr = "11.22.33.44";
                    //System.Net.IPAddress IPAddr = System.Net.IPAddress.Parse(addr);
                    ////网上的代码是得到字节组再转换成int
                    //byte[] byt = IPAddr.GetAddressBytes();
                    //int intIP = System.BitConverter.ToInt32(byt, 0);
                    //Console.WriteLine("字节转换结果:{0}", intIP);
                    ////其实GetHashCode()方法直接就可以了
                    IPAddress ClientIP   = (ReceiveSocket.RemoteEndPoint as IPEndPoint).Address;
                    int       ClientPort = (ReceiveSocket.RemoteEndPoint as IPEndPoint).Port;
                    ReceiveLength = ReceiveSocket.Receive(result);
                    string str = ReceiveSocket.RemoteEndPoint.ToString();
                    if (result[0] == 0)//接收消息
                    {
                        string ReceiveMessage = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1);
                        richTextBox1.Text += "接收客户端" + ClientIP.ToString() + "消息:" + DateTime.Now + "\r\n" + ReceiveMessage + "\r\n";
                        destination        = ServerSocket.LocalEndPoint.ToString();
                        source             = ClientIP.ToString();
                        mess = ReceiveMessage;
                        fo   = "rm";//视频格式
                        string record = "insert into recording (source,destination,datetime,message,format) " +
                                        "values('" + source + "','" + destination + "','" + DateTime.Now + "','" + mess + "','" + fo + "')";
                        MySqlCommand cmd = new MySqlCommand(record, mycon); //创建执行
                        cmd.ExecuteNonQuery();                              //执行SQL
                        mycon.Close();
                        mycon.Dispose();
                        //if (ClientInformation.Count == 1) continue;//只有一个客户端
                        List <string> test = new List <string>(ClientInformation.Keys);

                        /* for (int i = 0; i < ClientInformation.Count; i++)
                         * {//将接收到的消息群发出去,即所谓的群聊了
                         *   Socket socket = ClientInformation[test[i]];
                         *   string s = ReceiveSocket.RemoteEndPoint.ToString();
                         *   if (test[i] != s)
                         *   {
                         *       richTextBox1.Text += DateTime.Now + "\r\n" + "客户端" + str + "向客户端" + test[i] + "发送消息:\r\n";
                         *       byte[] arrMsg = Encoding.UTF8.GetBytes(ReceiveMessage);
                         *       byte[] SendMsg = new byte[arrMsg.Length + 1];
                         *       SendMsg[0] = 0;
                         *       Buffer.BlockCopy(arrMsg, 0, SendMsg, 1, arrMsg.Length);
                         *       socket.Send(SendMsg);
                         *   }
                         * }*/
                    }
                    if (result[0] == 6)//表示收到设备参数数据
                    {
                        Information = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1);
                        old_data    = Information;
                        RemoteDebug rd = new RemoteDebug();
                        if (Information != null)
                        {
                            if (Information[0] == '1')
                            {
                                rd.flag11 = true;
                            }

                            if (Information[1] == '1')
                            {
                                rd.flag22 = true;
                            }
                            if (Information[2] == '1')
                            {
                                rd.flag33 = true;
                            }

                            if (Information[3] == '1')
                            {
                                rd.flag44 = true;
                            }

                            if (Information[4] == '1')
                            {
                                rd.flag55 = true;
                            }

                            if (Information[5] == '1')
                            {
                                rd.flag66 = true;
                            }

                            if (Information[6] == '1')
                            {
                                rd.flag77 = true;
                            }

                            if (Information[7] == '1')
                            {
                                rd.flag88 = true;
                            }
                        }
                        richTextBox1.Text += "接收参数信息:" + Information + "\r\n";
                    }
                    if (result[0] == 1)//接收文件
                    {
                        try
                        {
                            richTextBox1.Text += "接收客户端:" + ReceiveSocket.RemoteEndPoint.ToString() +
                                                 "时间:" + DateTime.Now.ToString() + "\r\n" + "文件:\r\n";
                            SaveFileDialog sfd = new SaveFileDialog();
                            if (sfd.ShowDialog(this) == DialogResult.OK)
                            {
                                long   Rlength      = 0;
                                bool   flag         = true;
                                int    rec          = 0;
                                string fileSavePath = sfd.FileName;
                                richTextBox1.Text += "文件总长度为:" + FileLength.ToString() + "\r\n";
                                using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
                                {
                                    while (FileLength > Rlength)
                                    {
                                        if (flag)
                                        {
                                            fs.Write(result, 1, ReceiveLength - 1);
                                            fs.Flush();
                                            Rlength += (ReceiveLength - 1);
                                            flag     = false;
                                        }
                                        else
                                        {
                                            rec = ReceiveSocket.Receive(result);
                                            fs.Write(result, 0, rec);
                                            fs.Flush();
                                            Rlength += rec;
                                        }
                                    }
                                    richTextBox1.Text += "文件保存成功:" + fileSavePath + "\r\n";
                                    fs.Close();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("出现异常!");
                            ReceiveSocket.Shutdown(SocketShutdown.Both);
                            ReceiveSocket.Close();
                        }
                    }
                    if (result[0] == 5)
                    {
                        string fileNameWithLength = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1);
                        PictureLength      = Convert.ToInt64(fileNameWithLength.Split('-').Last());
                        richTextBox1.Text += "picturelength=" + PictureLength.ToString() + "\r\n";
                    }
                    if (result[0] == 2)//接收文件信息和长度
                    {
                        string fileNameWithLength = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1);
                        destination = ServerSocket.LocalEndPoint.ToString();
                        source      = ClientIP.ToString();
                        mess        = fileNameWithLength;
                        fo          = "rmbv";//视频格式
                        string record = "insert into recording (source,destination,datetime,message,format) " +
                                        "values('" + source + "','" + destination + "','" + DateTime.Now + "','" + mess + "','" + fo + "')";
                        MySqlCommand cmd = new MySqlCommand(record, mycon); //创建执行
                        cmd.ExecuteNonQuery();                              //执行SQL
                        mycon.Close();
                        mycon.Dispose();
                        //recStr = fileNameWithLength.Split('-').First();
                        FileLength         = Convert.ToInt64(fileNameWithLength.Split('-').Last());
                        richTextBox1.Text += "FileLength=" + FileLength.ToString() + "\r\n";
                    }
                    if (result[0] == 4)//收到图片的二进制信息
                    {
                        long Length = 0;
                        //MemoryStream ms = new MemoryStream();
                        bool flag1 = true;
                        int  rec   = 0;
                        ms = new MemoryStream();
                        while (Length < PictureLength)
                        {
                            //ReceiveLength = ReceiveSocket.Receive(buffer);
                            if (flag1)
                            {
                                ms.Write(result, 1, ReceiveLength - 1);
                                //ms.Flush();
                                Length += ReceiveLength - 1;
                                flag1   = false;
                            }
                            else
                            {
                                ReceiveLength = ReceiveSocket.Receive(result);
                                ms.Write(result, 0, ReceiveLength);
                                //ms.Flush();
                                Length += ReceiveLength;
                            }
                        }

                        /*Screen_Show screen_Show = new Screen_Show();
                         * screen_Show.pictureBox1.Image = Bitmap.FromStream(ms);
                         * //screen_Show.Show();
                         * //screen_Show.pictureBox1.Refresh();
                         * if (!flagg)//第一次打开显示图像窗体
                         * {
                         *  flagg = true;
                         *  screen_Show.StartPosition = FormStartPosition.Manual;
                         *  screen_Show.Show();
                         *  screen_Show.pictureBox1.Refresh();
                         * }
                         * else
                         * {
                         *  screen_Show.pictureBox1.Refresh();
                         *  Console.WriteLine("刷新picturebox\r\n");
                         * }*/
                    }
                    if (result[0] == 3)//表示收到客户端发送的心跳包,更新客户端最后在线时间
                    {
                        string ReceiveMessage = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1);
                        string str1           = "接收客户端心跳包:" + ReceiveMessage;
                        Console.WriteLine(str1);//将心跳包输出到后台
                        //发送应答包
                        string        SendMessage = "#####";
                        List <string> test        = new List <string>(ClientInformation.Keys);
                        for (int i = 0; i < ClientInformation.Count; i++)
                        {//给每个在线客户端发送应答消息
                            Socket socket  = ClientInformation[test[i]];
                            byte[] arrMsg  = Encoding.UTF8.GetBytes(SendMessage);
                            byte[] SendMsg = new byte[arrMsg.Length + 1];
                            SendMsg[0] = 3;
                            Buffer.BlockCopy(arrMsg, 0, SendMsg, 1, arrMsg.Length);
                            socket.Send(SendMsg);
                        }
                        try
                        {
                            string clientID  = ClientIP.ToString();
                            Int32  clientID2 = ClientIP.GetHashCode();//将IPAdress转换为int得到的是哈希码
                            lock (_DicClient)
                            {
                                try
                                {
                                    ClientInfo clientInfo;
                                    if (_DicClient.TryGetValue(clientID2, out clientInfo))//客户端已经上线
                                    {
                                        clientInfo.LastHeartbeatTime = DateTime.Now;
                                    }
                                    else
                                    {
                                        clientInfo          = new ClientInfo();
                                        clientInfo.ClientID = clientID;
                                        Console.WriteLine("加入集合中的clientInfo.ClientID={0}", clientInfo.ClientID);
                                        clientInfo.LastHeartbeatTime = DateTime.Now;
                                        clientInfo.State             = true;
                                        _DicClient.Add(clientID2, clientInfo);//加入集合
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("更新异常!" + ex.ToString());
                                    return;
                                }
                            }

                            /*ParameterizedThreadStart pts1 = new ParameterizedThreadStart(ReceiveHeartbeat);
                             * Thread thread = new Thread(pts1);
                             * thread.IsBackground = true;//设置后台线程
                             * thread.Start(ClientIP);*/
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    richTextBox2.Text += "监听出现异常!\r\n";
                    richTextBox2.Text += "客户端" + ReceiveSocket.RemoteEndPoint + "已经连接中断" + "\r\n" +
                                         ex.Message + "\r\n" + ex.StackTrace + "\r\n";
                    listBox1.Items.Remove(ReceiveSocket.RemoteEndPoint.ToString());//从listbox中移除断开连接的客户端
                    string s = ReceiveSocket.RemoteEndPoint.ToString();
                    ClientInformation.Remove(s);
                    ReceiveSocket.Shutdown(SocketShutdown.Both);
                    ReceiveSocket.Close();
                    break;
                }
            }
        }