public static ByteArrayToStructureEndian ( byte bytearray, object &obj, int startoffset ) : void | ||
bytearray | byte | |
obj | object | |
startoffset | int | |
return | void |
bool OnDataReceived(NFClientNet client, byte[] bytes, UInt32 bytesCount) { if (bytes.Length == bytesCount) { object structType = new MsgHead(); StructureTransform.ByteArrayToStructureEndian(bytes, ref structType, 0); MsgHead head = (MsgHead)structType; Int32 nBodyLen = (Int32)bytesCount - (Int32)ConstDefine.NF_PACKET_HEAD_SIZE; if (nBodyLen > 0) { byte[] body = new byte[nBodyLen]; Array.Copy(bytes, ConstDefine.NF_PACKET_HEAD_SIZE, body, 0, nBodyLen); client.net.mxBinMsgEvent.OnMessageEvent(head, body); return(true); } else { //space packet } } return(false); }
/// <summary> /// 接收到消息 /// </summary> void OnReceive(byte[] bytes, int length) { memStream.Seek(0, SeekOrigin.End); memStream.Write(bytes, 0, length); //Reset to beginning memStream.Seek(0, SeekOrigin.Begin); while (RemainingBytes() >= ConstDefine.NF_PACKET_HEAD_SIZE) { object structType = new MsgHead(); byte[] headBytes = new byte[Marshal.SizeOf(structType)]; Int32 msgheeadlen = Marshal.SizeOf(structType); Array.Copy(reader.ReadBytes(msgheeadlen), 0, headBytes, 0, msgheeadlen); StructureTransform.ByteArrayToStructureEndian(headBytes, ref structType, 0); MsgHead head = (MsgHead)structType; int datalen = (int)head.unDataLen - ConstDefine.NF_PACKET_HEAD_SIZE; if (RemainingBytes() >= datalen) { MemoryStream ms = new MemoryStream(); BinaryWriter writer = new BinaryWriter(ms); writer.Write(datalen); writer.Write(reader.ReadBytes(datalen)); ms.Seek(0, SeekOrigin.Begin); OnReceivedMessage(head.unMsgID, ms); } } //Create a new stream with any leftover bytes byte[] leftover = reader.ReadBytes((int)RemainingBytes()); memStream.SetLength(0); //Clear memStream.Write(leftover, 0, leftover.Length); }
void OnDataReceived() { if (mnPacketSize >= ConstDefine.NF_PACKET_HEAD_SIZE) { object structType = new MsgHead(); byte[] headBytes = new byte[Marshal.SizeOf(structType)]; Array.Copy(mPacket, 0, headBytes, 0, Marshal.SizeOf(structType)); StructureTransform.ByteArrayToStructureEndian(headBytes, ref structType, 0); MsgHead head = (MsgHead)structType; if (head.unDataLen == mnPacketSize) { byte[] body_head = new byte[head.unDataLen]; Array.Copy(mPacket, 0, body_head, 0, head.unDataLen); mnPacketSize = 0; if (false == OnDataReceived(client, body_head, head.unDataLen)) { OnClientDisconnect(new NFTCPEventParams()); } } else if (mnPacketSize > head.unDataLen) { UInt32 nNewLen = mnPacketSize - head.unDataLen; byte[] newpacket = new byte[ConstDefine.MAX_PACKET_LEN]; Array.Copy(mPacket, head.unDataLen, newpacket, 0, nNewLen); byte[] body_head = new byte[head.unDataLen]; Array.Copy(mPacket, 0, body_head, 0, head.unDataLen); mnPacketSize = nNewLen; mPacket = newpacket; if (false == OnDataReceived(client, body_head, head.unDataLen)) { OnClientDisconnect(new NFTCPEventParams()); } OnDataReceived(); } } }