I have coded a simple TCP chat in C language. The server's job is to receive messages from the client and to send them back in reverse order. The result should look like this:
Client: "Hello"
Server: "olleH"
When I apply "strlen()" to "olleH", the returned length is not 5, but 7. 7 is also the value returned by the read() function. What am I missing here? I know that char arrays end with a '\0', but that doesn't explain the 2 extra chars.
The loop should end upon receiving the message "FINISH". So, I compare the received message to the char array "FINISH" using strcmp(). They are never recognized as being the same for the reason exposed above. I am receiving a message with 2 extra chars. I've tried comparing the incoming message to "FINISH__" (interpret '_' as a blank space), but it won't work either.
do{
bzero(buffer, 1000);
n = read(client_socket, buffer, 1000);
if (n<0){
error("ERROR reading socket");
}
invert(buffer, inv); //inv is a buffer that stores the inverted array
n = write(client_socket, inv, n);
if (n<0){
error("ERROR writing in socket");
}
}while (strcmp(buffer, "FINISH\n") != 0);
Thank you for your help.
while sending data from server you must be typing
Hello
then pressingENTER
key which is nothing but\r\n
. So client is reading it asHello\r\n
. So you must be getting two characters extra. I hope it works for you. You can check this by looping through inputbuffer
and check whether\r\n
is present over there.