一般来说,我们使用Send发送结构体数据,结构体里面的数据,一般都是用定义好了的char 数组来发送的,如下例子:
struct Sendbuf
{
char encode; //数据编码格式。已定义:0:UTF-8,1:GBK,2:GB2312,3:ISO8859-1 4.
char encrypt; //加密类型。0表示不加密
char valuesEncode; //报文格式。0,string,1,json,2:xml;
char SendDate[1024]; //发送的数据 (一般没有特殊情况下,我们都是使用这种方式)
int length; //发送数据的长度
};
const char *msg = "Think You!!!"; //这里是要发送的内容
int SendDateklength = sizeof(Sendbuf) + strlen(msg)+1; //计算要发送的总的长度 (结构体长度+发送内容的长度)
Sendbuf SendDate;
SendDate.encode = 1;
SendDate.encrypt = 0;
SendDate.valuesEncode = 1;
SendDate.length = strlen(msg);
strcpy_s(SendDate.SendDate,strlen(msg) + 1,msg);
send(socket,(const char *)SendDate,SendDateklength,0);
这种方式局限很大,而且通用性也不强,比如说现在我要发送一个未知大小的数据怎么办,可能比sizeof(SendDate)更大,如果这种需求,上面的方法明显就不能用了,我把我的解决方法贴到下面,供大家参考:
struct Sendbuf
{
char encode; //数据编码格式。已定义:0:UTF-8,1:GBK,2:GB2312,3:ISO8859-1 4.
char encrypt; //加密类型。0表示不加密
char valuesEncode; //报文格式。0,string,1,json,2:xml;
char SendDate[1]; //发送的数据 (一般没有特殊情况下,我们都是使用这种方式)
int length; //发送数据的长度
};
const char *msg = "Think You!!!"; //这里是要发送的内容(msg是未知大小的内容)
int SendDateklength = sizeof(Sendbuf) + strlen(msg) +1; //这里是获取结构体的大小和发送内容的大小之和
Sendbuf *SendDate = (Sendbuf*)new char[SendDateklength ]; //new 出一个内存空间
SendDate->encode = 1;
SendDate->encrypt = 0;
SendDate->valuesEncode = 1;
SendDate->length = strlen(msg);
strcpy_s(SendDate->SendDate,strlen(msg) + 1,msg); //这里使用strcpy_s赋值
send(socket,(const char *)SendDate,SendDateklength,0); //Send
delete []SendDate; //发送完之后记得释放内存