C -不能查看recv返回的特定字符



我只需要读取以rnrn结尾的头的值

比如GETFILE OK 1024rnrn <content>

我试图获得第一个rn,然后在随后的接收呼叫中获得下一对。这个函数的调用是: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 rn pair
do {
    c = recv(gfr->client_fd, s, slen, 0);
    printf("checking to see what s has now: %sn", s);
    count += c;
} while ((c > 0) && (s[count - 1] != 'n'));
//get the second rn pair
count = 0;
do {
    c = recv(gfr->client_fd, s, slen, 0);
    printf("checking to see what s has now: %sn", s);
    count += c;
} while ((c > 0) && (s[count - 1] != 'n'));
printf("checking to see what s has now: %sn", 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] = '';
}
gfr->totalbytesReceived += count;
return c;
}

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

由于s是一个缓冲区(不是单个字符),对于第一个循环,比较方法可以更改为

while ((c > 0) && (strstr(s, "rn") == NULL));

同时要求"r" &有"n"。这利用了字符串搜索来检查两个值是否出现在一行中。

导致:

do {
    c = recv(gfr->client_fd, s, slen, 0);
    printf("checking to see what s has now: %sn", s);
    //  count += c; //not needed
} while ((c > 0) && (strstr(s, "rn") == NULL));

如果您决定捕获包含所有4的行,即rnrn,则将其作为比较的参数。

另一个注意事项,除非您将套接字选项设置为非阻塞,否则recv()是一个阻塞调用。查看如何将套接字设置为非阻塞

相关内容

  • 没有找到相关文章

最新更新