public void udpInit(string hostname, int port) { Random ran = new Random(); for (int i = 0; i < 10; i++) { try { theUDPSocket = new UdpClient(localPort); //theUDPSocket = new UdpClient(GTR_dnf.m_UDPPORT); break; } catch (Exception e) { localPort = ran.Next(6000, 8888); //GTR_dnf.m_UDPPORT = ran.Next(6000, 9999); } } RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); //RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, GTR_dnf.m_UDPPORT); //theUDPSocket = new UdpClient(RemoteIpEndPoint); IpSendPoint = new IPEndPoint(IPAddress.Parse(hostname), port); recS = new UdpState(); recS.udpClient = theUDPSocket; recS.ipEndPoint = RemoteIpEndPoint; UdpRecProc = new Thread(new ThreadStart(ReceiveMsg)); UdpRecProc.IsBackground = true; UdpRecProc.Start(); //theUDPSocket.Client.Blocking = false; //设置为非阻塞模式 //RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(hostname), port); //UdpRecProc = new Thread(new ThreadStart(UdpRecFun)); //UdpRecProc.Start(); }
// 接收回调函数 public void ReceiveCallback(IAsyncResult iar) { UdpState udpState = iar.AsyncState as UdpState; if (iar.IsCompleted) { try { m_recvData = udpState.udpClient.EndReceive(iar, ref recS.ipEndPoint); int type = 0; for (int i = 3; i >= 0; i--) { type = type * 256 + Convert.ToInt32(m_recvData[i]); } udpdata.udpSignal = type; udpdata.strOrderNO = MyStr.GetCut(Encoding.Default.GetString(m_recvData, 4, UDP_ORDERNO_LEN)); int num = 0; for (int i = 54; i < m_recvData.Length; i++) { if (m_recvData[i] == 0) { num = i; //Console.ReadKey(); break; } } udpdata.strData = MyStr.GetCut(Encoding.Default.GetString(m_recvData, UDP_ORDERNO_LEN + 4, num - 54)); LOL.m_strOrderData = udpdata.strData; //FileRW.WriteToFile("222\r\n"); switch (udpdata.udpSignal) { case 2: //TRANS_ORDER_DATA 订单数据 break; case 31: //TRANS_RES_IDCODE_RESULT 答题答案 break; case 36: //TRANS_SEND_MAIL 同意邮寄 LOL.IsAskMail = true; break; case 40: //TRANS_INSERT_ORDER 插入订单 theUDPSend(18, "申请插入订单:", LOL.OrdNo); break; case 51: LOL.bYiJiao = true; break; } receiveDone.Set(); } catch (Exception Err) { //FileRW.WriteToFile("111\r\n"); //throw Err; //uint IOC_IN = 0x80000000; //uint IOC_VENDOR = 0x18000000; //uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; //udpState.udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); } } }