Reputation: 11
I'm creating a game for a project, with a highscore server where the game can send commands to save a new highscore, get the top 10 score and so on. The problem I'm having is that after the game send a couple of command to the server, and they are executed perfectly fine, the call read()
just keeps receiving null
, even though the game isn't sending anything!!
I've searched around for a solution and I checked the following and they are OK:
1- when any socket is created, I check if (sockfd==-1)
and print an error and exit
2- I enabled blocking mode explicitly on every socket
3- I tested all the sockets
if(n < 0){
perror("Read Error:");
}
and it never enters here, but i changed to
if(n == 0){
perror("Read Error:");
}
and i get bad address!! Any help on how to have the read function to wait til the game actually executes a send?
Here is the send and read code that fails:
Server:
listen(sock, 5);
clientlength = sizeof(client_add);
newsock = accept(sock, (struct sockaddr *) &client_add, &clientlength);
if(newsock < 0){
printf("Couldn't accept\n");
}
while(1){
bzero(buffer, 300);
ioctl(newsock, FIONBIO, 0);
n= read(newsock, buffer, 299);
if(n == 0){
perror("Read Error:");
}
if(n<0){
printf("Error while reading from socket\n");
}
printf("Received: %s\n",buffer);
//send to function that processes the string
dothemagic(buffer);
}
An example of a sent msg:
strcpy(buffer, "gettop5");
n = write(sock,buffer,strlen(buffer));
if (n < 0){
printf("Writing to socket was unsuccessful\n");
}
Upvotes: 1
Views: 125
Reputation: 1357
The big problem is that your printf/perror only prints a message, but then execution continues (with the zeroed buffer...); you should instead print an error and then break from the loop/exit the program/whatever is appropriate. And like wildplasser pointed out, n==0 is not an error.
If you still can't figure it out, try with short, self contained, correct example -- it's impressive how often you'll realize the problem just by putting a sscce together!
Upvotes: 1