尝试基于套接字在 C 中编写 echo server\client。 我无法确定 fgets() 是如何工作的。
If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
while (fgets(sendline, MAXLINE, stdin) != NULL) {
sendline[strlen(sendline)-1] = '\0';
send(sockfd, sendline, strlen(sendline), 0);}
但是我在服务器上得到的是:
String received from and resent to the client:1234567890
String received from and resent to the client:abc
567890
如您所见,'\n' 字符添加到第二行,并尝试用新行覆盖第一行。但是在客户端,我看到缓冲区在使用 send() 时没有 '\n'。
按 ctld+D (EOF) 按预期工作。
如何预防?并使用 Enter 键发送?
最佳答案
当然接收端不是组成一个字符串,只是一个没有空字符的char
数组。发送 +1 以包含空字符。 @milevyo
while (fgets(sendline, sizeof sendline, stdin) != NULL) {
size_t length = strlen(sendline);
if (length > 0 && sendline[length-1] == '\n') {
sendline[--length] = '\0';
}
send(sockfd, sendline, length + 1, 0); // + 1
}
关于c - 读取 '\n' 后 fgets 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314299/