簡體   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