首页 > 学院 > 开发设计 > 正文

自定义协议封装包头、包体(待完善)

2019-11-06 09:03:03
字体:
来源:转载
供稿:网友
//定义包头        public struct Head        {            public int id;//协议Id            public long length; //包体长度        }        /// <summary>        /// 发送数据        /// </summary>        /// <param name="pid">协议Id</param>        /// <param name="body">包体</param>        public static void SendData(int pid, byte[] body)        {            Head mhead = new Head { id = pid, length = body.Length };            byte[] headbt = StructToBytes(mhead);            byte[] arrydata = new byte[headlength + body.Length];            Array.Copy(headbt, 0, arrydata, 0, headlength);            Array.Copy(body, 0, arrydata, headlength, body.Length);             if(clientSocket != null && clientSocket.Connected)//Socket实例            {                clientSocket.Send(arrydata);             }        }        /// <summary>          /// 接收数据          /// </summary>          /// <param name="socket"></param>          /// <param name="timeout"></param>          /// <returns></returns>          PRivate static string Receive(Socket socket, int timeout)//待完善        {            string result = string.Empty;            socket.ReceiveTimeout = timeout;            List<byte> data = new List<byte>();            byte[] buffer = new byte[1024];            int length = 0;            try            {                while ((length = socket.Receive(buffer)) > 0)                {                    for (int j = 0; j < length; j++)                    {                        data.Add(buffer[j]);                    }                    if (length < buffer.Length)                    {                        break;                    }                }            }            catch { }            if (data.Count > 0)            {                Receive_com(data.ToArray());                result = encode.GetString(data.ToArray(), 0, data.Count);            }            return result;         }        static bool isReadHead = true; //读包头        static byte[] headarry; //读包头        static int index = 0;//位置        static long bodylength;        static byte[] bodyarry; //读包体 缓存         /// <summary>        /// 读包解包        /// </summary>        /// <param name="data"></param>        static void Receive_com(byte[] data)        {            if (isReadHead)//读包头            {                if(data.Length >= headlength)                {                    headarry = new byte[headlength];                     Array.Copy(data, 0, headarry, 0, headlength);                    Head headm = (Head)BytesToStruct(headarry, typeof(Head));                    isReadHead = false;                    bodylength = headm.length;                    bodyarry = new byte[bodylength];                     if (data.Length > headlength)//读包体                    {                        byte[] bodyarry_ = new byte[data.Length - headlength];                        Array.Copy(data, headlength, bodyarry_, 0, bodyarry_.Length);                        Receive_com(bodyarry_);                     }                }            }            else//读包体            {                if(data.Length >= bodyarry.Length)                {                    Array.Copy(data, 0, bodyarry, index, data.Length - index);                    isReadHead = true; //读包头                    if (data.Length > bodyarry.Length)                    {                        byte[] headarry_ = new byte[data.Length + index - bodyarry.Length];                         Array.Copy(data, data.Length - index, headarry_, 0, headarry_.Length);                        Receive_com(bodyarry);                    }                                    }                else                {                    Array.Copy(data, 0, bodyarry, index, data.Length);                 }            }        }        /// <summary>          /// 销毁Socket对象          /// </summary>          /// <param name="socket"></param>          private static void DestroySocket(Socket socket)        {            if (socket.Connected)            {                socket.Shutdown(SocketShutdown.Both);            }            socket.Close();        }        //struct转换为byte[]        public static byte[] StructToBytes(object structObj)        {            int size = Marshal.SizeOf(structObj);            IntPtr buffer = Marshal.AllocHGlobal(size);             try            {                Marshal.StructureToPtr(structObj, buffer, false);                byte[] bytes = new byte[size];                Marshal.Copy(buffer, bytes, 0, size);                return bytes;            }            finally            {                Marshal.FreeHGlobal(buffer);            }        }        //byte[]转换为struct        public static object BytesToStruct(byte[] bytes, Type strcutType)        {            int size = Marshal.SizeOf(strcutType);            IntPtr buffer = Marshal.AllocHGlobal(size);            try            {                Marshal.Copy(bytes, 0, buffer, size);                return Marshal.PtrToStructure(buffer, strcutType);            }            finally            {                Marshal.FreeHGlobal(buffer);            }        }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表