UWP - 序列化结构以便使用TCP发送它

时间:2017-04-25 10:45:50

标签: serialization struct tcp enums uwp

我使用此代码的目的是将结构发送到服务器,该服务器等待此结构从中读取数据。所以我必须序列化所有引用,以便为服务器提供一个可以阅读和理解的结构。

我有一个包含long,ulong,string,enum,long []和其他结构的结构。我已经搜索了stackoverflow,但所有解决方案都将我的struct序列化为零,除了字符串。

如何正确地序列化结构,然后将其保存到byte []并最终使用tcp发送?

我的标题结构(that's why my struct looks like this):

  [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 4, Size = size)]
            public struct _HEADER 
            {
                [FieldOffset(0)]
                public Constants._TYPE Type;
                [FieldOffset(4)]
                public long Cr;
                [FieldOffset(12)]
                public Id Id;
                [FieldOffset(SIZE+12), MarshalAs(UnmanagedType.ByValArray)]  
                public long[] array;
            }

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Pack = 4, Size = SIZE)]
            public struct Id
            {
                [FieldOffset(0)]
                public long Protocol;
                [FieldOffset(8)]
                public long Protocol;
                [FieldOffset(16)]
                public Constants._TYPE CType;
                [FieldOffset(20)]
                public Constants._TYPE Cred;
                [FieldOffset(24)]
                public Constants._TYPE CGred;
            }

我的CURRENT方法来序列化结构:

    IntPtr pointer = Marshal.AllocHGlobal(Marshal.SizeOf(header));
    Marshal.StructureToPtr(header, pointer, false);
    byte[] headerdata = new byte[Marshal.SizeOf(header)];
    Marshal.Copy(pointer, headerdata, 0, headerdata.Length);
    Marshal.FreeHGlobal(pointer);

我发送数据的CURRENT方法:

_socket.Send(headerdata);

This is what I get in the tcp-packet, which I send to the server:

1 个答案:

答案 0 :(得分:0)