frmBarcodeControl.cs 17.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using MyClassLib;
using MyControlLib;
using HaierExe04;

namespace Weld
{
    public partial class frmBarcodeControl : MyFrmReg
    {
        public frmBarcodeControl()
        {
            InitializeComponent();
            this.Text =this.Text+ "--20181005 V2.2.2";
            DataInit();
         
        }
      

        #region
        private IPEndPoint ServerInfo;//存放服务器的IP和端口信息
        private Socket ServerSocket;//服务端运行的SOCKET
        private Socket Robot1_Socket;//
        private Socket Robot2_Socket;//
        private Socket Robot3_Socket;//
        private Thread ServerThread;//服务端运行的线程
        private Socket[] ClientSocket;//为客户端建立的SOCKET连接
        private int ClientNumb;//存放客户端数量
        private byte[] MsgBuffer;//存放消息数据

        private string ServerIp;//定义服务端IP地址
        private int LocalPort = 6000;//定义端口号

      
        #endregion

        #region  数据相关的初始化
        private void DataInit()
        {
            try
            {
                ServerIp = Properties.Settings.Default.ServerIP;
                string hostName = System.Net.Dns.GetHostName();
                System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostName);
                //IPAddress[] addresslist = Dns.GetHostByName(Dns.GetHostName()).AddressList;
                IPAddress[] addresslist = ipEntry.AddressList;
                int i = 0;
                bool flag = false;
                for (i = 0; i < addresslist.Length; i++)
                {
                    if (!addresslist[i].IsIPv6LinkLocal)
                    {
                        if (ServerIp == addresslist[i].ToString())
                        {
                            flag = true;
                        }
                        else
                        {
                            LogExecute.WriteInfoLog(string.Format("{0}获取的IP地址{1}", DateTime.Now.ToString(), addresslist[i].ToString()));
                        }
                    }
                }
                if (flag == false)
                {
                    LogExecute.WriteInfoLog("获取的网卡的IP地址中不存在服务器地址:" + ServerIp);
                    MessageBox.Show("获取的网卡的IP地址中不存在服务器地址:" + ServerIp);
                }

                LocalPort = Properties.Settings.Default.Port;
                timerScan.Interval = Properties.Settings.Default.Interval;
                txb_ip.Text = Properties.Settings.Default.ServerIP;
                txb_port.Text = LocalPort.ToString();

                timerScan.Enabled = false;
                //滚动条 初始化
                ucErrorDisplay1.MoveEnable = true;
                ucErrorDisplay1.Interval = 400;
                ucErrorDisplay1.SpeedMove = 25;

                //加载xml 文件
                //DirectoryInfo directory = new DirectoryInfo(Application.StartupPath+"/xmlfile");
                //XmlDocument xmlDocument = new XmlDocument();
                //xmlDocument.Load(Application.StartupPath + "/xmlfile/ext.xml");
                
            }
            catch (Exception ex)
            {
                LogExecute.WriteExceptionLog("DataInit", ex);
            }

        }


        #endregion
        #region
        /// <summary>
        ///  //开启服务器 侦听客户端的连接请求
        /// </summary>
        private bool SocketListen()
        {
            bool flag = false;
            try
            {
                ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //提供一个 IP 地址,指示服务器应侦听所有网络接口上的客户端活动
                //IPAddress ip = IPAddress.Any;

                IPAddress ip = IPAddress.Parse(ServerIp);
                ServerInfo = new IPEndPoint(ip, LocalPort);
                ServerSocket.Bind(ServerInfo);//将SOCKET接口和IP端口绑定
                ServerSocket.Listen(20);//开始监听,并且挂起数为25
                ClientSocket = new Socket[20];//为客服端提供连接个数
                MsgBuffer = new byte[65535];//消息数据的大小
                ClientNumb = 0;//客服端数据从0开始计数
                ServerThread = new Thread(new ThreadStart(RecieveAccept));//将接受客户端连接的方法委托给线程
                ServerThread.Start();//线程开始运行
                CheckForIllegalCrossThreadCalls = false;//不捕获对错误线程的调用


                string strWrite = "服务器" + ip.ToString() + "于" + DateTime.Now.ToString() + "开始运行" + "\r\n";
                txb_ip.Text = ip.ToString();
                txb_port.Text = LocalPort.ToString();
                txb_listenTime.Text = DateTime.Now.ToString();
                listBox1.Items.Add(strWrite);
                LogExecute.WriteInfoLog(strWrite);

                return true;
            }
            catch (Exception ex)
            {
                LogExecute.WriteExceptionLog("SocketListen", ex);
                return flag;
            }
        }

        /// <summary>
        /// //接受客户端连接的方法
        /// </summary>
        private void RecieveAccept()
        {
            while (true)
            {
                //Accept 以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket。
                //在阻止模式中,Accept 将一直处于阻止状态,直到传入的连接尝试排入队列。连接被接受后,原来的 Socket 继续将传入的连接请求排入队列,直到您关闭它。 
                //bool writeflag = false;
                try
                {
                    //todo:判断是否以前有该IP的连接
                    //string remoteEndPoint = ServerSocket.RemoteEndPoint.ToString();
                    //string ip=ServerSocket.RemoteEndPoint.ToString().Split(':')[0];
                    
                    //
                    ClientSocket[ClientNumb] = ServerSocket.Accept();
                    ClientSocket[ClientNumb].BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), ClientSocket[ClientNumb]);
                    string strWrite = "客户端" + ClientSocket[ClientNumb].RemoteEndPoint.ToString() + "于" + DateTime.Now.ToString() + "成功连接服务器";
                    
                    LogExecute.WriteInfoLog(strWrite);
                    string ippoint = ClientSocket[ClientNumb].RemoteEndPoint.ToString();
                    this.Invoke(new Action(()=> {
                        comboBox1.Items.Add(ippoint);
                        listBox1.Items.Add(strWrite);
                        listBox1.SelectedIndex = 0;
                    }));
                    ClientNumb++;
                    if(ClientNumb == 10)
                    {
                        ClientNumb = 0;
                    }
                    listBox1.Items.Add("ClientNumb:" + ClientNumb);
                }
                catch (SocketException ex)
                {
                    LogExecute.WriteExceptionLog("RecieveAccept", ex);
                }
            }
        }
        /// <summary>
        /// 条码长度
        /// </summary>
        private int barcodeLen = 10;
        /// <summary>
        /// 
        /// 帧格式开头
        /// </summary>
        private string barcodeSTX = ('\x02').ToString();
        /// <summary>
        /// 帧格式结束
        /// </summary>
        private string barcodeETX = ('\x03').ToString();
        /// <summary>
        /// //回发数据给客户端-
        /// </summary>
        /// <param name="AR"></param>
        private void RecieveCallBack(IAsyncResult AR)
        {
            lock (AR)
            {
                Socket RSocket = (Socket)AR.AsyncState;
                try
                {
                    int REnd = RSocket.EndReceive(AR);
                    string strRemoteIP = RSocket.RemoteEndPoint.ToString().Split(':')[0];
                    #region//1获取对应的IP地址 分析相应的处理

                    //step1: 确认是否为正确的条码信息
                    string strMsg = Encoding.ASCII.GetString(MsgBuffer).Substring(0, REnd);
                    string strIP = strRemoteIP;
                    if (strMsg != "")
                    {
                        // step2: 判断传入的数据为
                        this.Invoke(new Action(() =>
                        {
                            if (rtx_rec.TextLength >= 2000)
                            {
                                rtx_rec.Text = "";
                            }
                            rtx_rec.AppendText(strMsg);
                            ParseXmlInfo(RSocket, strMsg);
                            LogExecute.WriteLineDataLog(strMsg);

                        }));
                        //处理xml 字符串
                        //ParseXmlInfo(strMsg.Trim('\r').Trim('\n'));
                        
                    }
                    #endregion
                    if (RSocket.Poll(1000,SelectMode.SelectRead) == false)
                        RSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);
                }
                catch (Exception ex)
                {
                    if (ex is SocketException)
                    {
                        SocketException soex = (SocketException)ex;
                        LogExecute.WriteExceptionLog(soex.ErrorCode + ":" + soex.Message, ex);
                        //if (soex.ErrorCode == 10053)//客户端主动关闭10053
                        //{
                        //    RSocket.Close();
                        //}
                        //if (soex.ErrorCode == 10054)//客户端主动关闭10054
                        //{
                        //    RSocket.Close();
                        //}
                    }
                    else
                    {
                        LogExecute.WriteExceptionLog("receievecallback", ex);
                        RSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);
                    }

                } 
            }


        }


        #endregion

        #region 自定义函数
        /// <summary>
        /// 解析xml 字符串
        /// </summary>
        /// <param name="str_xml"></param>
        private void ParseXmlInfo(Socket socket, string str_xml)
        {
            // XmlDocument xml = new XmlDocument();
            // xml.LoadXml(str_xml);
            //XmlNodeList nodeList= xml.GetElementsByTagName("send");
            string ip ="192.168.2.10";
           // foreach (Socket socket in ClientSocket)
           // {
           //     if (socket is null) continue;
           //     if (!IsSocketConnected(socket)) continue;
                if (socket.RemoteEndPoint.ToString().Split(':')[0] != null)
                {
                    try
                    {
                        byte[] sends = ASCIIEncoding.ASCII.GetBytes(rtx_send.Text);
                        socket.Send(sends);
                        textBox1.Text = "发送:" + rtx_send.Text;
                        listBox1.Items.Add(string.Format("Time:{0}RemoteIP:{1} send:{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), ip, rtx_send.Text));
                        if (listBox1.Items.Count > 100)
                        {
                            listBox1.Items.Clear();
                        }
                        hanlerInfo(socket, str_xml);
                        LogExecute.WriteInfoLog(rtx_send.Text);
                    }
                    catch (SocketException ex)
                    {
                        listBox1.Items.Add(ex.Message);
                        Console.WriteLine(ex.Message);
                    }
            //        break;
           //     }
            }
        }

        private bool IsSocketConnected(Socket s)
        {
            return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected);
        }

        private void hanlerInfo(Socket socket, string message)
        {
            if(message == HaierExe04.Constant.ROBOT_CONNECT)
            {
                XmlNode node = GetXmlValue(HaierExe04.Constant.ROBOT_CONNECT, "Pra[10]");
             //   listBox1.Items.Add("str:" + str);
                listBox1.Items.Add("机器人发送Hellon");
                socket.Send(ASCIIEncoding.ASCII.GetBytes(Constant.SERVER_SEND));
            }
            if(message == HaierExe04.Constant.ROBOT_ASK_TESK)
            {
                listBox1.Items.Add("上位机就绪,准备发送任务");
            }
        }

        public XmlNode GetXmlValue(string xml, string tag)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<PData><CODE>11</CODE><NAME>kkkk</NAME></PData>");
            XmlNode rootNode = xmlDoc.SelectSingleNode("PData");
            foreach (XmlNode xxNode in rootNode.ChildNodes)
            {
                string TAG = xxNode.Name;
                string value = xxNode.InnerText;
                listBox1.Items.Add("TAG:" + TAG + " value:" + value);
            }
            return rootNode;
        }


        #endregion

        /// <summary>
        /// 定时器事件函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerScan_Tick(object sender, EventArgs e)
        {
            try
            {
               
               
            }
            catch (Exception ex)
            {
                LogExecute.WriteExceptionLog("TimerScan", ex);
            }
        }

        /// <summary>
        /// 开启服务程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                if (SocketListen() == true)
                {
                    toolStripButton2.Enabled = false;
                    toolStripButton1.Enabled = true;
                    timerScan.Enabled = true;
                }
                else
                {
                    toolStripButton1.Enabled = false;
                    toolStripButton2.Enabled = true;
                    timerScan.Enabled = false;
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        /// <summary>
        /// 关闭服务程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            try
            {
                if (ServerThread.IsAlive)
                {
                    ServerThread.Abort();
                    ServerSocket.Close();
                    //MasterPLC2.Close();
                }
            }
            catch (Exception ex)
            {
                LogExecute.WriteExceptionLog("ServerThread", ex);
            }
            finally
            {
                toolStripButton2.Enabled = true;
                timerScan.Enabled = false;
            }
        }
       

        /// <summary>
        /// 退出系统
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmBarcodeControl_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show(this, "你确定要退出系统,系统将无法运行", this.Text, MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                e.Cancel = false;
                if (ServerThread.IsAlive)
                {
                    ServerThread.Abort();
                    ServerSocket.Close();
                    //ServerThread.close();
                }
               
            }
            else
            {
               
                e.Cancel = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string ip = comboBox1.SelectedItem.ToString();
            foreach (Socket socket in ClientSocket)
            {
                if (socket is null) continue;
                if (socket.RemoteEndPoint.ToString().Split(':')[0] == ip)
                {
                    byte[] sends = ASCIIEncoding.ASCII.GetBytes(rtx_send.Text);
                    socket.Send(sends);
                    listBox1.Items.Add(string.Format("Time:{0}RemoteIP:{1} send:{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), ip, rtx_send.Text));
                    if (listBox1.Items.Count > 100)
                    {
                        listBox1.Items.Clear();
                    }
                    LogExecute.WriteInfoLog(rtx_send.Text);
                }
            }
        }

        //导入Excel 
        private void toolStripSplitButton3_ButtonClick(object sender, EventArgs e)
        {
           
        }

        private void cbx_clear_CheckedChanged(object sender, EventArgs e)
        {
            rtx_rec.Text = "";
        }

        private void txb_ip_TextChanged(object sender, EventArgs e)
        {

        }

        private void frmBarcodeControl_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}