简体   繁体   English

从套接字读取字符串时,不打印第一个字符

[英]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. 如您所见,第一个'H'未打印。

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. 尝试将“ \\ n”放在printf()语句的末尾 ,它更干净,将帮助您进行调试。
  2. You are also sending the newline, that's why there are 13 bytes at write() ; 您还发送了换行符,这就是为什么write()处有13个字节的原因; 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. 总而言之,我认为您会获得“ H”字样,但打印不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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