/* 远程端口与本地端口一致*/ public void SetPara() { try { if (udpServer != null) { udpServer.Close(); udpServer = null; } //本机节点 //ipEndPoint = new IPEndPoint(IPAddress.Parse(hostIp), ipPort); //本地测试 ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), FrmMain.systemP.wireControlport); //绑定服务器的ip和端口号 udpServer = new UdpClient(ipEndPoint); UdpState s = new UdpState(udpServer, ipEndPoint); udpServer.BeginReceive(EndReceive, s); } catch (Exception exc) { FrmMain.T.queueIn(DateTime.Now.ToString("yy-MM-dd HH-mm-ss f") + exc.ToString() + "SetPara"); } }
/// <summary> /// 异步接收 /// </summary> /// <param name="ar"></param> public void EndReceive(IAsyncResult ar) { try { if (Model == "test") { msgShow1(DateTime.Now.ToString("yy-MM-dd HH:mm:ss fff---") + "开始接收数据......"); } else { //FrmMain.T.queueIn(DateTime.Now.ToString("yy-MM-dd HH:mm:ss fff---") + "开始接收数据......"); } UdpState s = ar.AsyncState as UdpState; if (s != null) { UdpClient udpClient = s.udpclient; IPEndPoint ip = s.IP; if (true) { Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip); int length = receiveBytes.Length / 4; Int32[] array = new Int32[length]; bool N = ConvertByteAToIntA(receiveBytes, ref array); if (!N) { FrmMain.T.queueIn(DateTime.Now.ToString("yy-MM-dd HH:mm:ss fff---") + "接收的数据错误"); } else { if (Model == "test") { msgShow1(array[0].ToString() + ";" + array[1].ToString() + ";" + array[2].ToString() + ";" + array[3].ToString()); } if (array[0] != 0 & array[1] != 0 & array[2] != 0 & array[3] != 0) { FrmMain.T.queueIn(DateTime.Now.ToString("yy-MM-dd HH:mm:ss fff---") + "数据接收成功:" + array[0].ToString() + ";" + array[1].ToString() + ";" + array[2].ToString() + ";" + array[3].ToString()); //FrmMain.frmMain.tBoxGlassId.Text = array[0].ToString(); if (array[1].ToString() != FrmMain.frmMain.tboxGlassLength.Text || array[2].ToString() != FrmMain.frmMain.tboxGlassWidth.Text || array[3].ToString() != FrmMain.frmMain.tboxGlassThick.Text) { if (ShowMessage != null) //说明有人订阅了事件 { ShowMessage(this, array); //将udp接收到的玻璃信息传递给FrmMain } productInfoChanged = true; } } else { FrmMain.T.queueIn(DateTime.Now.ToString("yy-MM-dd HH:mm:ss fff---") + "数据接收失败:"); } //Program.frmain.UDPStatue.Text = "通讯状态:数据已接收"; //Program.frmain.GlassId.Text = "当前玻璃ID:" + Convert.ToString(FloatPara.R_progressiveID); } array = null;//释放; } udpClient.BeginReceive(EndReceive, s); } } catch (Exception ex) { FrmMain.T.queueIn(DateTime.Now.ToString("yy-MM-dd HH:mm:ss fff---") + "数据接收错误:" + ex); // T.queueIn(DateTime.Now.ToString("yy-MM-dd HH:mm:ss fff---") + "数据接收错误:" + ex); } }