1

我是新来的。我有一个问题,我完全不知道是什么原因造成的!我希望有人能帮助我。我正在开发一个带有套接字的小型 TCP 服务器,它接收来自客户端的字符串并且必须在其上做一些事情。程序在这个函数中保持阻塞,永远不会返回:

int parse_request(char * request, char *start, char**headers, char *body)

该函数的核心是2个嵌套strtok()的组合:

line = strtok_r (request, "\n", &saveptr1);
while (line != NULL) {

    if (strcmp(line, "\r\n") == 0 || strcmp(line, "\r") == 0) bdy = 1;
    else {
        if (i == 1) {
            /* the first line (command) */
            printf("linea iniziale: ");
            start = line;
            start[strlen(line)] = '\0';
            printf ("%s\n",start);
            printf("\n");
        }
        else {
            if (bdy == 0) {
                /* the headers */
                temp = line;
                subline = strtok_r (temp, ":", &saveptr2);
                head = subline;
                head[strlen(subline)] = '\0';
                subline = strtok_r (NULL, ":", &saveptr2);
                if (subline != NULL) {
                    value = subline;
                    value[strlen(subline)] = '\0';
                    }
                else value = "none";

                if (strcmp(head, "Connection") == 0 && strcmp(value, "close") == 0) retval = 0;
                if (strcmp(head, "Content-Length") == 0) ignoreboby = 0;

                headers[j] = head;
                headers[j+1] = value;
                printf("header -> %s : %s\n", headers[j], headers[j+1]);
                j = j + 2;
            }
            else {
                headers[j] = '\0';
                if (ignoreboby != 1){
                    /* the body */
                    printf("body: ");
                    body = line;
                    body[strlen(line)] = '\0';
                    printf ("%s\n",body);
                }
                else {
                    body = "\0";
                    **printf("body ignored\n");**
                }
            }
        }
    }
    //printf("kkk");
    line = strtok_r (NULL, "\n", &saveptr1);
    i++;
}

程序在打印“body被忽略”或“Body: %s\n, body”后立即阻塞。

有人有想法吗?我真的很麻烦!谢谢

编辑:这可能是我创建和传递参数的方式是真正的问题吗?

char command[] = "\0", body[] = "\0";
char **headers;
headers = malloc(8192);
        if (!headers) {
            printf("Error in malloc()");
            closesocket(s);
        }
int x = parse_request(buf, command, headers, body);
4

1 回答 1

0

那是因为你没有改变line,所以你被困在while循环中。

于 2013-08-28T15:47:51.897 回答