我正在尝试通过套接字发送结构(我意识到这是一个不可移植的解决方案,但是,客户端和服务器只是Windows - 如果有一个相当容易实现更便携的解决方案,我' m up for it)。
这个系统向另一个套接字发送一个双打结构,服务器只是一个重定向器。现在,前几个结构正常,但在某些时候,我开始得到垃圾数据,我无法弄清楚原因。
以下是客户端的代码:
struct aircraft_data {
double altitude;
double indicated_airspeed;
double radio_altitude;
double ground_altitude;
double vertical_speed;
double bank_angle;
double pitch;
double stall_aoa;
double aoa;
double on_ground;
double sideslip;
double heading_mag;
double heading_true;
double track_mag;
double track_true;
double eng_1_epr;
double eng_2_epr;
double eng_1_n1;
double eng_2_n1;
double eng_1_n2;
double eng_2_n2;
double thr_1_pos;
double thr_2_pos;
double yoke_x_pos;
double yoke_y_pos;
double rudder_pedal_pos;
double rudder_pos;
double elevator_pos;
double aileron_pos;
double latitude;
double longitude;
double velocity_body_x;
double velocity_body_y;
double velocity_body_z;
double rotation_velocity_body_x;
double rotation_velocity_body_y;
double rotation_velocity_body_z;
};
接收结束:
while (kill_dataproc == FALSE) {
if(master == FALSE) {
char* buffer = new char[4096];
int recvd = recv(data_sock, buffer, 4096, NULL);
if (recvd == 4096) {
int sz = sizeof(aircraft_data);
int intsz = sizeof(int);
int newpacketsigner = 0;
memcpy_s(&newpacketsigner, intsz, buffer, intsz);
if (newpacketsigner == 1192) {
memcpy_s(cdata, sz, (void*)(buffer + intsz), sz); //cdata is another struct of the same type - this part works, it usually doesn't get here.
}
}
delete buffer;
}
Sleep(50);
}
发送端(称为回调函数的一部分):
char* buff = new char[4096];
int packet_signer = 1192;
int sz = sizeof(aircraft_data);
int intsz = sizeof(int);
memcpy_s(buff, intsz, &packet_signer, intsz);
memcpy_s((void*)(buff + intsz), sz, data, sz);
send(data_sock, (char*)buff, 4096, NULL);
delete buff;
服务器(在循环中完成 - 该方法可行,因为我已经与其他二进制服务器(即VoIP)一起使用:
char* fbuffer = new char[4096];
int recvdf = recv(gp->users[i].sockfd_data, fbuffer, 4096, NULL);
if (recvdf > 0)
gp->send_to_all(fbuffer, i, 1, recvdf);
delete fbuffer;
我觉得有必要补充一点,如果我尝试在任何套接字上设置TCP_NODELAY,它会导致同样的问题,并且减少发送线程的Sleep()时间似乎也会导致它。