gpt4 book ai didi

c++ - Winsock 2,将变量压缩成一个字符串,发送出去,然后接收并读回

转载 作者:行者123 更新时间:2023-11-28 04:52:43 24 4
gpt4 key购买 nike

我正在编写一些涉及使用惯性立方体跟踪器的代码,它会主动改变其偏航俯仰和滚动(以度为单位),我需要设置一个服务器来读取该信息以便将信息联网。到目前为止,我已经创建了一个客户端和服务器,但我遇到的问题是要么在一个 block 中发送信息,然后将其作为三个 block 读回并打印,要么指定哪个发送与哪个接收匹配。

if( currentTrackerH > 0 )
{
int iSendResult1;
int iSendResult2;
int iSendResult3;

char EulerBuffer0[64];
char EulerBuffer1[64];
char EulerBuffer2[64];


showStationData( currentTrackerH, &TrackerInfo,
&Stations[station-1], &data.Station[station-1],
&StationsHwInfo[currentTrackerH-1][station-1],
showTemp);
//send to the server
do{
sprintf(EulerBuffer0, "%f", data.Station[station-1].Euler[0]);
iSendResult1= send(Connection, EulerBuffer0, sizeof(data.Station[station-1].Euler[0]), NULL);

sprintf(EulerBuffer1, "%f", data.Station[station-1].Euler[1]);
iSendResult2= send(Connection, EulerBuffer1, sizeof(data.Station[station-1].Euler[1]), NULL);

sprintf(EulerBuffer2, "%f", data.Station[station-1].Euler[2]);
iSendResult3= send(Connection, EulerBuffer2, sizeof(data.Station[station-1].Euler[2]), NULL);
}while ((iSendResult1 || iSendResult2 || iSendResult3)>0);
//shutdown the socket when there is no more data to send
iSendResult1 = shutdown(Connection, SD_SEND);
if (iSendResult1 == SOCKET_ERROR)
{
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(Connection);
WSACleanup();
return 1;
}
}
}

这是我的客户端,在这里我将放置我的服务器端。网络连接,我的跟踪器代码工作正常,但发送和接收是一切变得不稳定的地方。

//begin recieving data
char yaw[256];
char pitch[256];
char roll[256];

int iResult1;
int iResult2;
int iResult3;

float fyaw, fpitch, froll;

do{
do {
iResult1= recv(newConnection, yaw,sizeof(yaw),NULL);
} while( iResult1 == 0 );

fyaw = atof(yaw);

do {
iResult2= recv(newConnection, pitch,sizeof(pitch),NULL);
} while( iResult1 == 0 );

fpitch = atof(pitch);

do {
iResult3= recv(newConnection, roll,sizeof(roll),NULL);
} while( iResult1 == 0 );

froll = atof(roll);

printf("(%f,%f,%f)deg \n",
fyaw, fpitch, froll);
}while(1);

我对 C++ 的了解并不多,如果有任何帮助,我将不胜感激。谢谢!

最佳答案

您的代码中存在各种错误。让我们尝试打破并纠正误解(我假设您使用的是 TCP。)您正在发送一种大小的缓冲区,但可能正在接收另一种大小的缓冲区。 sizeof(yaw) 是一个 float ,与此 float 的字符串表示形式的大小不同。

为单个项目调用发送/接收很慢。理想情况下,您会定义一个简单的协议(protocol)。此协议(protocol)中的消息将是包含您希望传输的所有值的字符串。您使用单个 send() 发送该消息 在接收端,您读取数据流,并查找告诉您何时收到完整消息的特定标记。然后您处理该消息,将不同的组件拆分为您的偏航/俯仰/滚动变量。

字符串消息的示例是:"{yaw=1.34;pitch=2.45;roll=5.67}"

然后在客户端上,您不断地将数据读入缓冲区,直到到达“}”,然后您可以处理此消息并解析出不同的组件。

关于c++ - Winsock 2,将变量压缩成一个字符串,发送出去,然后接收并读回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47816451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com