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

时间:2015-06-08 19:53:40

标签: c websocket webclient recv

我只需要读取以\r\n\r\n

结尾的标头的值

GETFILE OK 1024\r\n\r\n <content>

这样的东西

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

问题:当我知道它们存在时,引用\n的while中的逻辑被完全忽略,或者没有显示任何匹配。这是比较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;
}

1 个答案:

答案 0 :(得分:0)

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

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

while ((c > 0) && (strstr(s, "\r\n") == NULL));

同时要求&#34; \ r&#34; &安培; &#34; \ n&#34;在那儿。这利用字符串搜索来检查一行中是否存在两个值。

导致:

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