我正在使用此 tcp_read 函数从套接字读取消息:
ssize_t tcp_read(int fd, void *buf, size_t count)
{
size_t nread = 0;
while (count > 0) {
int r = read(fd, buf, count);
if (r < 0 && errno == EINTR)
continue;
if (r < 0)
return r;
if (r == 0)
return nread;
buf = (unsigned char *) buf + r;
count -= r;
nread += r;
}
return nread;
}
在 server.c 文件中,我正在创建一个猜词游戏,我正在使用此 tcp_read 函数读取来自用户的消息,该函数接近真正的 read()强>。
用户将输入类似以下内容:“L: someword\r\n”,我将按以下方式阅读此内容:
char read[strlen(token2)+5];
char *token2 = "someword"
int n = tcp_read(cfd, read, strlen(token2)+5);
read[n] = '\0';
char *s;
size_t len = strlen(read);
s = malloc(len);
strcpy(s, read+3); //to cut 'R: '
s[len - 4] = 0;
tcp_write(cfd, s, strlen(s));
if(strcmp(token2, read) == 0)
{
tcp_write(cfd, beg_o, strlen(beg_o));
}else
{
tcp_write(cfd, beg_f, strlen(beg_f));
}
token2 是用户应该猜测的单词。 beg_o 和 beg_f 只是一些“恭喜”和“你失败了”的打印。
我执行了 strlen(token2) + 5,因为 token2 是用户应该猜测的单词 + 5 个字符,表示 'R' ':' ' ' '\r' '\n',因为这 5 个字符是每个用户输入的内容总是相同的,只有某个词是动态的。
在第一次迭代中它可以工作,但是当再次调用该函数时它不再工作(因为代码的第二部分处于一个大循环中)
但我无法理解为什么这不起作用,有时它有效有时会失败,例如用户输入“L:someword\r\n”并且我的函数中的读取不是>someword,但有时是somew,有时只是so。它的行为很奇怪。
最佳答案
我很惊讶它能编译,只是看看它。动态数组暗淡是一个扩展,您可能应该避免它 - 只需执行 char read[1024] 或其他操作即可。 (实际上你应该使用 #define
来实现这一点。)但无论如何,token2
甚至没有在第一行定义,所以我不知道动态如何可以评估数组暗淡。
一旦克服了这个问题,就可以使用调试器。逐行检查变量,直到发现哪里出了问题。
关于c - 从套接字读取然后分割输入字符串在 C 中的行为不正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347314/