C#与C++通过socket传送结构体

C#服务端:
 1 using System;
 2 using System.Net.Sockets;
 3 using System.Net;
 4 using System.IO;
 5 using System.Diagnostics;
 6 using System.Threading;
 7 using System.Runtime.InteropServices;
 8
 9
10
11
12
13 [StructLayout(LayoutKind.Sequential, Pack = 1)]
14          public  struct PaketHead
15          {
16            public UInt32 OPCode;
17            public byte DiskFlag;
18            public long DiskSize;
19            public long OPOffSet;
20            public long OPByteCount;
21
22            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
23            public byte[] Authentic;
24            public byte Encrypt;
25            public byte Ver;
26            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
27            public byte[] AddIn;
28            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
29            public byte[] Reserve;
30            public byte Zero;
31            public int SizeOfHead;
32        }

33
34          protected  byte[] Struct2Bytes<T>(T obj)
35          {
36            int size = Marshal.SizeOf(obj);
37            byte[] bytes = new byte[size];
38            IntPtr arrPtr = Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0);
39            Marshal.StructureToPtr(obj, arrPtr, true);
40            return bytes;
41        }

42
43          protected T Bytes2Struct<T>( byte[] bytes)
44          {
45            IntPtr arrPtr = Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0);
46            return (T)Marshal.PtrToStructure(arrPtr, typeof(T));
47        }
 
48
49          protected  void ReadPacketHead(BinaryReader ClientReader, BinaryWriter ClientWriter)
50          {
51            byte[] test = null;
52            test = ClientReader.ReadBytes(180);
53
54            PaketHead Paket = Bytes2Struct<PaketHead>(test);
55
56            Console.WriteLine(Paket.OPCode);
57            Console.WriteLine(Paket.DiskFlag);
58            Console.WriteLine(Paket.DiskSize);
59            Console.WriteLine(Paket.OPOffSet);
60            Console.WriteLine(Paket.OPByteCount);
61            Console.WriteLine(System.Text.Encoding.ASCII.GetString(Paket.Authentic));
62            Console.WriteLine(Paket.Encrypt);
63            Console.WriteLine(Paket.Ver);
64            Console.WriteLine(System.Text.Encoding.ASCII.GetString(Paket.AddIn));
65            Console.WriteLine(System.Text.Encoding.ASCII.GetString(Paket.Reserve));
66            Console.WriteLine(Paket.Zero);
67            Console.WriteLine(Paket.SizeOfHead);
68            /
69            test = Struct2Bytes<PaketHead>(Paket);
70            ClientWriter.Write(test);
71        }

72
73

 

C++ Client:

 

  1 #include <winsock2.h>
  2 #pragma comment( lib, "ws2_32.lib" )
  3
  4 #pragma pack(push, 1) // 取消内存大小自动对齐
  5
  6 typedef  struct _PaketHead2
  7 {
  8    UINT OPCode;/
  9    UCHAR DiskFlag;//
 10    __int64 DiskSize;////
 11    __int64 OPOffSet;////
 12    __int64 OPByteCount;/////
 13    UCHAR    Authentic[64];//
 14    UCHAR    Encrypt;////
 15    UCHAR    Ver;
 16    UCHAR    AddIn[64];//
 17    UCHAR    Reserve[16];////
 18    UCHAR    Zero;///
 19    UINT SizeOfHead;/
 20}
PaketHead2,*pPaketHead2;
 21
 22 #pragma pack(pop)
 23
 24 // template <class T>
 25 // void ConvertToByteArray(T arg,unsigned char * Buffer) 
 26 // {
 27 //     for (int i=0;i<sizeof(T); i++)
 28 //     {
 29 //         int offset = i*8;
 30 //         Buffer[i] = (arg& (0xff << offset)) >> offset;
 31 //     }
 32 // }
 33 //
 34 // template <class T>
 35 // T ConvertBytesTo(byte *buf) 
 36 // {
 37 //     T ret = 0x0;
 38 //     for (int i=0;i<sizeof(T); i++) 
 39 //     {
 40 //         int offset = i*8;
 41 //         ret |= buf[i] << offset;
 42 //     }
 43 //     return (ret);
 44 // }
 45
 46 int ConnTest()
 47 {
 48    SOCKET mySocket;
 49    WORD wVersionRequested;
 50    WSADATA wsaData;
 51    int err;
 52
 53    wVersionRequested = MAKEWORD( 2, 2 );
 54
 55    WSAStartup( wVersionRequested, &wsaData );
 56
 57    try
 58    {
 59        err = WSAStartup( wVersionRequested, &wsaData );
 60        if ( err != 0 ) {
 61            printf("Couldn't find a WinSock DLL\n");
 62            return 1;
 63        }

 64
 65        if ( LOBYTE( wsaData.wVersion ) != 2 ||
 66            HIBYTE( wsaData.wVersion ) != 2 ) 
 67        {
 68            printf("Couldn't find the right version for WinSock 2.2\n");
 69            WSACleanup( );
 70            return 1; 
 71        }

 72
 73        SOCKADDR_IN          ServerAddr;
 74
 75        mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 76        ServerAddr.sin_family = AF_INET;
 77        ServerAddr.sin_port = htons(8021);    
 78        ServerAddr.sin_addr.s_addr = inet_addr("192.168.0.5");
 79
 80
 81        if (connect(mySocket, (SOCKADDR *) &ServerAddr, sizeof(ServerAddr))) 
 82        {
 83            int error_code = WSAGetLastError();
 84            printf("Error connecting socket: %d\n",error_code);
 85            return 1;
 86        }

 87
 88        /
 89
 90        PaketHead2 testhead2;
 91
 92        memset(&testhead2,0x00,sizeof(PaketHead2));
 93
 94        testhead2.DiskFlag = 0x1;
 95        testhead2.OPCode = 9856;
 96        testhead2.DiskSize = 78954612;
 97        testhead2.OPOffSet = 98643217;
 98        testhead2.OPByteCount = 85642311;
 99
100        memcpy(testhead2.Authentic,"9876543210ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghij1234567\0",64);
101        memcpy(testhead2.AddIn,"9876543210ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghij1234567\0",64);
102        memcpy(testhead2.Reserve,"abcdefghij12345\0",16);
103
104        testhead2.Encrypt = 0x2;
105        testhead2.Ver = 0x4;
106        testhead2.Zero = 0x0;
107        testhead2.SizeOfHead = sizeof(PaketHead2);
108
109        send(mySocket,(char*)(&testhead2),sizeof(PaketHead2),NULL);
110
111        memset(&testhead2,0x00,sizeof(PaketHead2));
112        recv(mySocket,(char*)(&testhead2),sizeof(PaketHead2),NULL);
113
114        /*testhead2.Authentic[63] = 0;
115        testhead2.AddIn[63] = 0;
116        testhead2.Reserve[15] = 0;*/

117
118        printf("%d\n",testhead2.OPCode);
119        printf("%d\n",testhead2.DiskFlag);
120
121        printf("%ld\n",testhead2.DiskSize);
122        printf("%ld\n",testhead2.OPOffSet);
123        printf("%ld\n",testhead2.OPByteCount);
124
125        printf("%s\n",testhead2.Authentic);
126        printf("%d\n",testhead2.Encrypt);
127        printf("%d\n",testhead2.Ver);
128
129        printf("%s\n",testhead2.AddIn);
130        printf("%s\n",testhead2.Reserve);
131        
132        printf("%d\n",testhead2.Zero);
133
134        printf("%d\n",testhead2.SizeOfHead);
135        //
136        closesocket(mySocket);
137        WSACleanup( );
138    }

139    catch()
140    {
141        printf("Error!\n");
142    }

143}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值