private void CalcHeaderCrc(ref GamePackHeader header, byte[] dst) { int headerCrcSize = Marshal.SizeOf(header.headerCrc32); int sz = Marshal.SizeOf(header) - headerCrcSize; mCrc.Crc(dst, headerCrcSize, sz); header.headerCrc32 = (uint)mCrc.Value; byte[] crc = BitConverter.GetBytes(header.headerCrc32); Buffer.BlockCopy(crc, 0, dst, 0, crc.Length); }
/// <summary> /// 消息分发 /// </summary> /// <param name="packet"></param> private void OnPacketDistributeEvt(GamePacket packet) { //校验crc //headcrc和datacrc都需要校验 TODO //这里对datacrc校验一下 byte[] data = packet.data; mCrc.Crc(data); uint dataCrc = (uint)mCrc.Value; if (packet.header.dataCrc32 == dataCrc) { ByteBuffer buffer = new ByteBuffer(); buffer.WriteBytes(packet.data); KeyValuePair <int, ByteBuffer> _event = new KeyValuePair <int, ByteBuffer>(packet.header.header, buffer); //facade.SendMessageCommand(NotiConst.DISPATCH_MESSAGE, _event); } else { Debug.LogError("发送方,接收方 的数据不一致"); //抛弃还是重新请求?TODO } }
public bool Send(string ip, int port, byte[] buf, int packetHandle, int bufSize = -1) { if (string.IsNullOrEmpty(ip) || port <= 0) { return(false); } if (bufSize < 0 && buf != null) { bufSize = buf.Length; } bool hasBufData = (buf != null) && (bufSize > 0); GamePackHeader header = new GamePackHeader(); if (hasBufData) { header.dataSize = bufSize; } else { header.dataSize = 0; } header.header = packetHandle; if (hasBufData) { mCrc.Crc(buf, bufSize); header.dataCrc32 = (uint)mCrc.Value; } else { header.dataCrc32 = 0; } int headerSize = Marshal.SizeOf(header); int dstSize = headerSize; if (hasBufData) { dstSize += bufSize; } // 下面注释是未优化代码 //byte[] dstBuffer = new byte[dstSize]; // 此处已优化 var dstStream = NetByteArrayPool.GetByteBufferNode(dstSize); try { byte[] dstBuffer = dstStream.GetBuffer(); // 此处可优化,可以考虑后续使用RINGBUF优化,RINGBUF用完可以自动关闭掉连接 IntPtr pStruct = Marshal.AllocHGlobal(headerSize); try { Marshal.StructureToPtr(header, pStruct, false); Marshal.Copy(pStruct, dstBuffer, 0, headerSize); #if USE_NETORDER // Calc header Crc CalcHeaderCrc(ref header, dstBuffer); // used net header.headerCrc32 = (uint)IPAddress.HostToNetworkOrder(header.headerCrc32); header.dataCrc32 = (uint)IPAddress.HostToNetworkOrder(header.dataCrc32); header.header = IPAddress.HostToNetworkOrder(header.header); header.dataSize = IPAddress.HostToNetworkOrder(header.dataSize); Marshal.StructureToPtr(header, pStruct, false); Marshal.Copy(pStruct, dstBuffer, 0, headerSize); #endif } finally { Marshal.FreeHGlobal(pStruct); } #if USE_NETORDER #else // Calc header Crc // CalcHeaderCrc(ref header, dstBuffer); #endif if (hasBufData) { Buffer.BlockCopy(buf, 0, dstBuffer, headerSize, bufSize); } return(SendBuf(ip, port, dstBuffer, dstSize)); } finally { if (dstStream != null) { dstStream.Dispose(); dstStream = null; } } }