|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Winsock Recv Problems
Okay, I'm stuck on how fix the bug I currently have with my recv.
The code I have is: Code:
void sTheGame::RecieveData() {
for (std::vector<sClient*>::iterator it = PlayerList.begin(); it != PlayerList.end(); ++it) {
sClient *Client = (*it);
if (FD_ISSET(Client->Socket, &Client->SocketData)) {
char buffer[256];
Client->AddressLen = recv(Client->Socket, buffer, 256, 0);
if (Client->AddressLen == 0) {
// Data Fail, Disconnect Client
}
else if (Client->AddressLen > 0) {
sOutput(buffer);
}
}
}
}
Code:
class sClient {
public:
eConnectionState ConnectionState; // TODO: Enum
char *PlayerName;
int IncorrectPassword;
int Room;
SOCKET Socket;
sockaddr_in Address;
int AddressLen;
fd_set SocketData;
sClient();
~sClient();
void Init();
// int Get_Socket() { return s; }
bool Connected;
bool IsPlaying;
};
sOutput is a class function that does: printf("%s\n", buffer); As you can see from the screen dump, I get a load of jibberish, how do I correct this? |
|
#2
|
||||
|
||||
|
> As you can see from the screen dump, I get a load of jibberish, how do I correct this?
By storing a \0 in the string before you print it. recv() doesn't add this for you. Code:
char buffer[256];
Client->AddressLen = recv(Client->Socket, buffer, sizeof(buffer)-1, 0);
if (Client->AddressLen == 0) {
// Data Fail, Disconnect Client
}
else if (Client->AddressLen > 0) {
buffer[Client->AddressLen] = '\0';
sOutput(buffer);
}
The -1 in the size allows room to append a \0 even if recv() fills the buffer.
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Winsock Recv Problems |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|