繁体   English   中英

无法查看recv返回的特定字符

[英]cannot look at specific char returned by recv

我只需要读入以\\r\\n\\r\\n结尾的标头的值

类似于GETFILE OK 1024\\r\\n\\r\\n <content>

我正在尝试获取第一个\\r\\n ,然后在后续的recv调用中获取第二对。 该函数的调用是: read_in_header(gfr, headerRecvBuff, 1);

问题:当我知道\\n存在时,在引用\\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;
}

关于这是比较char换行符的正确方法吗?

由于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()是阻塞调用。 研究如何将套接字设置为非阻塞

暂无
暂无

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

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