send()默认第二个参数只能发送char*类型数据,怎么发送一个结构体呢?
方法一:
定义一个结构体,实例化结构体对象。通过memcpy()给结构体变量的成员赋值,这样是直接赋值到对象所在的内存中。
代码如下:
struct SNewStruct
{
char lenth[10];
char str[20];
};
//发送数据
char SendBuf[500];
memset(SendBuf, 0, sizeof(SendBuf));
//memset(&newstruct, 0, sizeof(newstruct));
//newstruct.lenth=sizeof(newstruct.str)-1;
memcpy(newstruct.lenth, "10", sizeof("10"));
memcpy(newstruct.str, "send struct test", sizeof("send struct test"));
int len=sizeof(newstruct);
send(SockClient, (char *)&newstruct, len, 0);
接收端代码:
//接收数据
char RecvBuf[200];
memset(RecvBuf, 0, sizeof(RecvBuf));//清空接收缓存
recv(NewSocket, RecvBuf, sizeof(RecvBuf), 0);
memset(&newstruct, 0, sizeof(newstruct));//清空结构体
memcpy(&newstruct, RecvBuf, sizeof(newstruct));
//打印数据
//printf("%s\n",RecvBuf);
printf("%s\n",newstruct.lenth);
printf("%s\n",newstruct.str);
方法二:
定义一个结构体,结构体内部用构造函数对数据成员进行初始化,再实例化结构体变量。将结构体变量地址强制转换为(char *),最后通过send()发送
代码如下:
struct SNewStruct
{
public :
int lenth;
char str[3];
SNewStruct()
{
lenth=10;
str[0]='z';
str[1]='b';
str[2]='\0';
}
};
//发送数据
char SendBuf[500];
int len=sizeof(newstruct);
printf("%d\n",newstruct.lenth);
send(SockClient, (char *)&newstruct, len, 0);
接收端代码:
//接收数据
char RecvBuf[200];
memset(RecvBuf, 0, sizeof(RecvBuf));//清空接收缓存
recv(NewSocket, RecvBuf, sizeof(RecvBuf), 0);
SNewStruct *p=(SNewStruct *)RecvBuf;
//打印数据
printf("%d\n",p->lenth);
printf("%s\n",p->str);