我只需要读入以 \r\n\r\n
结尾的 header 的值
类似于 GETFILE OK 1024\r\n\r\n <content>
我正在尝试获取第一个 \r\n
然后在后续的 recv 调用中获取下一对。
对该函数的调用是:read_in_header(gfr, headerRecvBuff, 1);
问题:引用 \n
时的逻辑当我知道它们存在时,它被完全忽略,或者不显示任何匹配项。这是比较 char 换行符的正确方法吗?
int read_in_header(gfcrequest_t *gfr, char *buf, int len) {
char *s = buf;
int slen = len;
int c = 0;
int count = 0;
//get the first \r\n pair
do {
c = recv(gfr->client_fd, s, slen, 0);
printf("checking to see what s has now: %s\n", s);
count += c;
} while ((c > 0) && (s[count - 1] != '\n'));
//get the second \r\n pair
count = 0;
do {
c = recv(gfr->client_fd, s, slen, 0);
printf("checking to see what s has now: %s\n", s);
count += c;
} while ((c > 0) && (s[count - 1] != '\n'));
printf("checking to see what s has now: %s\n", s);
if (c < 0) {
return c;
} else if (c == 0) {
puts("Time to disconnect, the server is done.");
//total bytes received should not include header length
gfr->totalbytesReceived -= gfr->headerbytes_received;
return 0;
} else {
s[c - 1] = '\0';
}
gfr->totalbytesReceived += count;
return c;
}
最佳答案
关于这是比较字符换行符的正确方法吗?
由于 s 是一个缓冲区(不是单个字符),因此对于第一个循环,比较方法可以更改为
while ((c > 0) && (strstr(s, "\r\n") == NULL));
要求“\r”和“\n”都在那里。这利用字符串搜索来检查两个值是否出现在一行中。
结果:
do {
c = recv(gfr->client_fd, s, slen, 0);
printf("checking to see what s has now: %s\n", s);
// count += c; //not needed
} while ((c > 0) && (strstr(s, "\r\n") == NULL));
如果您决定捕获包含全部 4 个值的行,即 \r\n\r\n
,则将其作为比较的参数。
旁注,除非您将套接字选项设置为非阻塞,否则 recv() 是阻塞调用。调查 how to set a socket to non-blocking
关于无法查看recv返回的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30717887/