private static void ReceiveMsg() { while (isOn) { // 用来保存发送方的ip和端口号 EndPoint point = new IPEndPoint(IPAddress.Any, 0); byte[] buffer = new byte[1024]; // 接收数据报 try { int length = socket.ReceiveFrom(buffer, ref point); Cat021Data outData = CommWrapper.decode(buffer, UDPDataSource.type); qData.Enqueue(outData); } catch (Exception) { return; } } }
public static Cat021Data decode(Byte[] msg, Byte type) { if (null == msg || 0 == msg.Length) { Cat021Data exceptionData = new Cat021Data(); exceptionData.sModeAddress = -1; exceptionData.flightNo = "CA0000"; return(exceptionData); } try { msg[1023] = type; // Console.WriteLine("msg1 = " + msg[0] + ", " + msg[1] + ", " + msg[2]); var p = Marshal.AllocHGlobal(1024); Marshal.Copy(msg, 0, p, 1024); IntPtr ptr = CommWrapper.decodeMessage4(p); Marshal.FreeHGlobal(p); msg[1023] = 0; // Console.WriteLine("msg2 = " + msg[0] + ", " + msg[1] + ", " + msg[2]); Cat021Data outData = (Cat021Data)Marshal.PtrToStructure(ptr, typeof(Cat021Data)); if (-1 == outData.sModeAddress) { Cat021Data exceptionData = new Cat021Data(); exceptionData.sModeAddress = -1; exceptionData.flightNo = "CA0000"; return(exceptionData); } // Marshal.FreeHGlobal(ptr); return(outData); } catch { Cat021Data exceptionData = new Cat021Data(); exceptionData.sModeAddress = -1; exceptionData.flightNo = "CA0000"; return(exceptionData); } }