Common problems in project 5
From our experience, here is the overwhelming problem in this project:
One application is putting more bytes into the socket than the other application is reading.
Example: client asks the user if they want to play again. User types yes[Enter]
fgets reads in 'y' and 'e' and 's' and '\n' and adds a '\0' after the newline. So the length of this string is 4.
n=write(sockfd, buffer, strlen(buffer)); // n=4
Then, let's say your server reads one byte to determine if the user sent y or n.
That leaves 3 bytes in the socket. The next time that the server goes to read from the socket, it will not block waiting for data to read. It will have 3 bytes to read and it will. That is a problem because 'e' 's' '\n' is not what the server is expecting at this point.
Another issue:
If you do this:
n=write(sockfd, buffer, strlen(buffer));
Do not expect to be able to use strcmp to check to see if the strings are equal. strlen does NOT include the '\0' in the length of the string. So the above write will not write '\0'. Therefore, the read at the other end of the socket will not read a C string. There are ways to get around this, such as filling the buffer with '\0' or 0 before the read. That ensures that there will be a null terminator after the data so it can be handled as a string. But you should be aware.
Bottom line:
If one app. write n bytes. Make sure the other reads n bytes.
And be aware of what the final character is. Is it '\n' or '\0' or something the user typed in. If you are aware, then you can program the receiving end to deal with it effectively.
- Login to post comments
