简体   繁体   中英

When reading string from a socket, the first character is not printed

The input from the user is insert to 'buffer'.

Code

while(1)
 {
     puts("\n#listening");

     puts("#Enter your message:");
     fgets(buffer,255,stdin);
     int n = write(s,buffer,strlen(buffer));// char buffer[512];
     printf("\n>> Writing to server: %d bytes",n);

     int r = read(s,buffer,strlen(buffer));
     if(r > 0)
     {
             printf("\n>> Reading from server: %d :%s",r,buffer);
     }
 }

Output

#listening
#Enter your message:
Hello World!

>> Writing to server: 13 bytes
>> Reading from server: 12 :ello World!

As you can see the first 'H' is not printed.

There are problems with this code, but none of them would drop the first character in a received message.

It is the "server" program on the far end of the socket which is responsible for losing the character.

  1. Try to put the "\\n" at the end of printf() statements, it's cleaner and will help you in debugging.
  2. You are also sending the newline, that's why there are 13 bytes at write() ; that might mess up with the way you're printing on the console.

All in all, I think you are getting the "H" back but you're not printing it right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM