Reputation: 25
Struct I want to send:
struct Client
{
SOCKET socket = 0;
float m_fX = 0;
float m_fY = 0;
float m_fRot = 0;
bool m_bIsAlive = false;
Powerups m_ePowerup = Powerups::lazer;
};
Client Sending Struct to Server:
char* buffer = new char[sizeof(Client)];
memcpy(buffer, &dataToServer, sizeof(Client));
send(sock, (char*)dataToServer, sizeof(Client), NULL);
Server Receiving Struct from Client:
char* buffer = new char[sizeof(Client)];
recv((SOCKET)socketData, buffer, sizeof(Client), NULL);
memcpy(m_pClients[i], (void*)buffer, sizeof(Client));
std::cout << "\tSocket: " << (int)(SOCKET)socketData << "\t" << m_pClients[i]->m_bIsAlive << std::endl;
Why does this print out as though m_pClients[i]->m_bIsAlive = 205?
Upvotes: 1
Views: 1155
Reputation: 118425
char* buffer = new char[sizeof(Client)];
memcpy(buffer, &dataToServer, sizeof(Client));
send(sock, (char*)dataToServer, sizeof(Client), NULL);
Looks to me like you meant for the second parameter to send() to be buffer
, here. Additionally, if dataToServer
is a pointer to a Client
structure, the second parameter to memcpy()
should not be a pointer to this pointer.
Additionally, your code fails to check the return value from both send() and recv() also. Just because you asked to send sizeof(Client)
bytes, you have absolutely no guarantee whatsoever that this request will succeed, or that many bytes will be written.
The same thing goes for recv
() too. You must always check the return value from every system call, be prepared to handle errors and every possible return value, unless external circumstances (there are few cases like that) guarantee that the system call will never fail.
Upvotes: 1