日期:2014-05-18  浏览次数:21085 次

c# udp通信中用结构体序列化后报文大小取不到,请教
发送接收代码:
C# code

 private void SendData()
        {
            UdpClient MyUdpClient = new UdpClient();
            IPAddress remoteIp;
            if (IPAddress.TryParse(txt_RemotIp.Text.Trim(),out remoteIp) == false)
            {
                MessageBox.Show("错误", "远程ip地址格式不对");
                return;
            }
            IPEndPoint iep = new IPEndPoint(remoteIp, port);
            byte[] bytes = proData();
            try
            {
                MyUdpClient.Send(bytes, bytes.Length,iep);
                MyUdpClient.Close();
            }
            catch (Exception ex)
            {
                LogHelper.WriteError("SendData_catch", ex.Message);
                MessageBox.Show("发送失败","错误");
            }
            finally
            {
                MyUdpClient.Close();
            }
        }
 private void ReceiveDate()
        {
            udpClient = new UdpClient(port);
            IPEndPoint remote = null;
            while (true)
            {
                try
                {
                    byte[] bytes = udpClient.Receive(ref remote);
                    UnPackUdp_data(bytes);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteError("ReceiveDate_catch", ex.Message);
                    break;
                }
            }
        }

 private UDP_data Data(int packIndex,int type)
        {
            byte[] btmp=Encoding.UTF8.GetBytes(txt_SendMsg.Text.Trim());

            UDP_data sd = new UDP_data();
            sd.packIndex = packIndex;
            sd.type = type;
            sd.data = btmp;

            sd.length = btmp.Length;
            return sd;
        }
        private void UnPackUdp_data(byte[] bytes)
        {
            string str = "报文大小:" + bytes.Length.ToString();
            UDP_data rd = new UDP_data();
            rd = (UDP_data)BytesToStruts(bytes, typeof(UDP_data));

            str = str + ",包序号:" + rd.packIndex.ToString();
            str = str + ",包类型:" + rd.type.ToString();
            str = str + ",数据体长:" + rd.length.ToString();
            str = str + ",内容:" + Encoding.UTF8.GetString(rd.data);
            AddListReceive(str);

            LogHelper.WriteInfo("", str);
            LogHelper.WriteInfo("", BitConverter.ToString(bytes));
        }
        private byte[] proData()
        {
            // return Pack(1, 1, Encoding.UTF8.GetBytes(txt_SendMsg.Text.Trim()));
            return StrutsToBytesArray(Data(0,1));
        }
public struct UDP_data
        {
            public int packIndex;//包序号
            public int type;//数据类型
            public int length;//数据长度
            public byte[] data;//数据体
            //public byte crc;
        }
 /// <summary>
        /// 结构体到byte[]
        /// </summary>
        /// <param name="structObj"></param>
        /// <returns></returns>
        public static byte[] StrutsToBytesArray(object structObj)
        {
            //得到结构体的大小
            int size = Marshal.SizeOf(structObj);
            //创建byte数组
            byte[] bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            //从内存空间拷到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }
        /// <summary>
        /// byte[]到结构体
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="type"></