我正在接收字符串並將其保存到輸入緩衝區中。這是流和字符串可能不完整,所以我正在查找最後一個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 ;
}