我遇到的问题是,接收的数据转成结构体后,结构体读取值不对,只有ret是对的,代码如下:
int ret = recv(deviceInfo.sockClient, (char *)(&recebuf), sizeof(recebuf), 0); //第二个参数使用强制类型,为一个数据包
SendStcuct *data_send=new SendStcuct; data_send->size = size; data_send->error_code = 999; data_send->data_type = 2; data_send->cam_no = deviceInfo.cam_no; memcpy(data_send->sendbuf, data, size); //int iRet = send(deviceInfo.socket, (char *)&data_send, sizeof(SendStcuct)-1, 0); char sendbuf[1516]; memset(sendbuf, 0, 1516); int count = 0; memcpy(sendbuf, &((*data_send).size), sizeof(data_send->size)); count += sizeof(data_send->size); memcpy(sendbuf + count, &(data_send->data_type), sizeof(data_send->data_type)); count += sizeof(data_send->data_type); memcpy(sendbuf + count, &(data_send->error_code), sizeof(data_send->error_code)); count += sizeof(data_send->error_code); memcpy(sendbuf + count, &(data_send->cam_no), sizeof(data_send->cam_no)); count += sizeof(data_send->cam_no); memcpy(sendbuf + count, data_send->sendbuf, sizeof(data_send->sendbuf)); count += sizeof(data_send->sendbuf); /*char sendbuf[1516]; memset(sendbuf, 0, 1516); memcpy(sendbuf, data_send, sizeof(SendStcuct));*/ int iRet = send(deviceInfo.socket, (char *)(sendbuf), count, 0);
struct Test { char ip[30]; char name[30]; };
发送双方都需定义好此结构体。
接收:
Test te;
char buff[1024];
//清空
memset(buff, 0, 1024);
memset(&te, 0x00, sizeof(Test));
//直接接收结构体,可行 recv(serConn, (char*)(&te), sizeof(Test), NULL);
//内存拷贝,程序崩溃。将字符串大小改成buff[100]后可行,查阅后,别人解释说是因为申请的栈过大
//还可通过配置属性->c/c++->代码生成->基本运行时检查 设置为默认值解决。
//memcpy(&te, buff, sizeof(buff));
//接收char*,然后转成结构体,可行 recv(serConn,buff, sizeof(buff), NULL); te = *(Test*)buff; printf("ip=%s,name=%s\n", te.ip,te.name);
发送:
Test cp; memset(&cp, 0x00, sizeof(Test)); memcpy(cp.ip,"192.168.0.1",sizeof("192.168.0.1")); memcpy(cp.name, "hello", sizeof("hello")); send(sockClient, (char*)(&cp), sizeof(Test),NULL);
