2013-12-21 41 views
0

我正在接收字符串并将其保存到输入缓冲区中。这是流和字符串可能不完整,所以我正在查找最后一个STOP - 字符串,复制其余(这是下一个块的开始)并追加复制数据后面的下一个传递的数据。
中间我对输入缓冲区做了一些操作(如memcpy)。我应该制作一个输入缓冲区的副本,还是可以使用input_buffer?从流中连续接收数据并读取流

有人告诉我,这将是毫无意义:

if (bytes_received == 0) { 
     continue; 
    } 

但是,这是流。如果这没有意义,我怎么能保证,我会不断接收数据?

char * strrstr(char *string, char *find, ssize_t len) 
{ 

    char *cp;  
    for (cp = string + strlen(string) - 4; cp >= string; cp--) 
    { 
    if (strncmp(cp, find, 4) == 0) 
    return cp+4; 
    } 
    return NULL; 
} 

int main (void) { 
    char * input_buffer = malloc(MAXLENGTH); 
    size_t restSize=0; 
    char * restP; 

    int socket_handle = reqData(subStr); 
    ssize_t bytes_received ; 
    for (;;) { 

    bytes_received = recv (socket_handle , input_buffer+restSize ,MAXLENGTH-1, 0) ; 

    input_buffer[bytes_received-1] = '\0'; 
    if (bytes_received == -1) { 
     printf ("-1 An error occured during the receive procedure \n") ; 
     return 0 ; 
    } 
    if (bytes_received == 0) { 
     printf ("0 An error occured during the receive procedure \n") ; 
     return 0 ; 
    } 
    restP = strrstr (input_buffer, STOP, 4); 
    if (restP == NULL) 
    { 
     restSize = 0; 
     continue; 
    } 
    restSize = strlen(restP);//MAXLENGTH - (restP - input_buffer) + 1; 
    processXML(input_buffer, restP, t); 
    strcpy(input_buffer, restP); 

    } 
    close(socket_handle); 
    free (input_buffer); 
    return 0 ; 
} 

回答

2

有在你的代码的一些错误:

  1. 这里:input_buffer[bytes_received-1] = '\0';你不检查,如果bytes_recived是-1(你以后做)。此外,您必须检查它是否为0,因为数组的负索引是不允许的。哟,以后也是这样,所以只要移动引用的行。

  2. 考虑从string.h中使用strstr函数而不是strrstr。即使你的实现看起来很好(如果这是一个很好的练习,如果这是一个很好的练习),建议使用标准函数,因为它们比实现更安全,可能会隐藏一些错误。

  3. 当调用recv函数时,不需要期望MAXLENGTH-1。 MAXLENGTH也可以。

现在回答你的问题,这可能是有用的:recv() returns 0 正如你看到的,当recv的返回0,则在期待输入了没有意义的。