C#通過TCP接收后反序列化結(jié)構(gòu)我通過TCP接口發(fā)送我自己的struct“packet”對象,C#通過TCPListener和TCPClient提供。這是我的結(jié)構(gòu)[Serializable]struct RemuseNetworkPacket{
public String ApplicationCode;
public String ReceiverCode;
public RemusePacketType Type;
public uint ID;
public uint cID;
public String Name;
public byte[] Data;
public String Text;
public System.Drawing.Point Coords;
public String Timestamp;
public String Time;
public String SenderName;
public byte[] Serialize()
{
var buffer = new byte[Marshal.SizeOf(typeof(RemuseNetworkPacket))];
var gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
var pBuffer = gch.AddrOfPinnedObject();
Marshal.StructureToPtr(this, pBuffer, false);
gch.Free();
return buffer;
}
public void Deserialize(byte[] data)
{
var gch = GCHandle.Alloc(data, GCHandleType.Pinned);
this = (RemuseNetworkPacket)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(RemuseNetworkPacket));
gch.Free();
}}我在結(jié)構(gòu)中使用序列化方法來準(zhǔn)備和檢索發(fā)送之前和之后的數(shù)據(jù)。為了讓接收器知道輸入數(shù)據(jù)的大小,我將一些頭數(shù)據(jù)添加到正在發(fā)送的字節(jié)中,格式為l = 212; ...這意味著長度= 212; 而...是數(shù)據(jù)包的其余部分。在接收端,我搜索這個,直到找到整個l = xxxx; 然后我創(chuàng)建一個沒有標(biāo)題的新字節(jié)數(shù)組,然后嘗試反序列化數(shù)據(jù)。用于反序列化的數(shù)據(jù)包字節(jié)是:tcp stream的buffer.Length - foundHeaderSize (l = xxxx;)如果我在同一臺機(jī)器上運(yùn)行客戶端和服務(wù)器,它可以正常運(yùn)行,但是如果我將客戶端和服務(wù)器放在不同的機(jī)器上,我會遇到異常并且崩潰。數(shù)據(jù)包被反序列化時發(fā)生異常,說:* System.Runtime.InteropServices.SafeArrayTypeMismatchException數(shù)組的運(yùn)行時類型與System.Runtime.InteropServices.PtrToStructureHelper中元數(shù)據(jù)中記錄的sb類型之間發(fā)生不匹配Stacktrace:System.Runtime.InteropServices.PtrToStructure的System.Runtime.InteropServices.PtrToStructureHelper(IntPtr ptr,Object structure,Boolean allowValueClasses)(IntPtr ptr,Type structureType .. *我正在尋求幫助以確定問題的原因。對于通過網(wǎng)絡(luò)傳輸?shù)膶ο螅也荒苓@樣做嗎?
- 2 回答
- 0 關(guān)注
- 594 瀏覽
添加回答
舉報
0/150
提交
取消