这就是我到目前为止所做的一切:
struct HeadPacket
{
int type;
};
struct ReceivePacket
{
// Header
HeadPacket Head;
// Raw Data
char* buffer;
};
struct MovePacket
{
// Header
HeadPacket Head;
// Raw Data
float X;
float Y;
};
struct ClientsPacket
{
// Header
HeadPacket Head;
// Raw Data
int Clients;
float* X;
float* Y;
};
这些是我有的一些例子。
首先,我创建一个数据包,将其转换为char *并发送它。
MovePacket m;
m.Head.type = 2;
m.X = X;
m.Y = Y;
this->Socket->Send(this->Socket->GetAddress(), (char*)&m, sizeof(m));
另一方面,我收到了它:
char packet[256]; //max size of a packet
SOCKADDR_IN server;
this->Socket->Receive(packet, 256, &server);
现在我将它转换为数据包以便读取类型,然后我将其转换为
ReceivePacket* rec = (ReceivePacket*)packet;
switch (rec->Head.type)
{
case 0:
{
MovePacket* move = (MovePacket*)rec;
}
break;
case 1:
{
ClientsPacket* c = (ClientsPacket*)rec;
}
break;
}
如果我发送和接收MovePacket,一切正常。
但是如果我发送一个具有float数组的ClientsPacket,则float数组永远不会包含正确的值。
ClientsPacket c;
c.Head.type = 3;
c.Clients = clients.size();
c.Y = new float[clients.size()];
c.X = new float[clients.size()];
int size = sizeof(c.Head) + sizeof(int)+((sizeof(float)*clients.size()) * 2);
for (unsigned int i = 0; i < clients.size(); i++)
{
c.X[i] = clients[i].X;
c.Y[i] = clients[i].Y;
printf("X: %f Y: %f\n", c.Y[i], c.X[i]);
}
rc = sock.Send(newclient.GetAddr(), (char*)&c, size);
你知道如何解决它,以及我可以进一步阅读它为什么会发生的地方,或者你可以向我解释它为什么会发生?
答案 0 :(得分:0)
它应该是什么样子: 服务器:
ClientsPacket c;
c.Head.type = 3;
c.Clients = clients.size();
c.X = new float[clients.size()];
c.Y = new float[clients.size()];
//define sizes
int fsize = (sizeof(float)*clients.size());
int hsize = sizeof(c.Head) + sizeof(c.Clients);
int size = hsize + sizeof(float)+(fsize*2);
//define sendchar
char* buffer = new char[size];
//fill arrays
for (unsigned int i = 0; i < clients.size(); i++)
{
c.X[i] = clients[i].X;
c.Y[i] = clients[i].Y;
printf("X: %f Y: %f\n", c.X[i], c.Y[i]);
}
//copy memory from client
memcpy(buffer, &c, hsize);
memcpy(buffer + hsize, c.X, fsize);
memcpy(buffer + hsize + fsize, c.Y, fsize);
客户端:
ClientsReceivePacket* cv = (ClientsReceivePacket*)rec;
ClientsPacket c;
memcpy(&c.Head, packet, sizeof(c.Head));
memcpy(&c.Clients, packet + sizeof(c.Head), sizeof(c.Clients));
c.X = new float[cv->Clients];
c.Y = new float[cv->Clients];
//define sizes
int hsize = sizeof(c.Head) + sizeof(c.Clients);
int fsize = (sizeof(float)*c.Clients);
//copy content into float array
memcpy(c.X, packet + hsize, fsize);
memcpy(c.Y, packet + hsize + fsize, fsize);