我正在开发一个需要解析分块类型 HTTP 传输的客户端。我用头撞墙试图找出以下错误,如果有人能够更快地发现我的错误,我将不胜感激。总结一下这个问题:似乎客户端没有收到所有的 block ,从而搞砸了其余的过程。提前致谢!
while(cflag){
pfile_chunk = malloc(CHUNK_SIZE+1);
memset(pfile_chunk, 0, CHUNK_SIZE);
cPtr = pfile_chunk;
cPtr2 = NULL;
k=0;
while(*(cPtr-1) != '\n'){
k++;
recv(sock, cPtr, 1, 0);
cPtr = pfile_chunk+k;
}
cPtr2 = strchr(pfile_chunk, '\r');
*cPtr2 = '\0';
sscanf(pfile_chunk, "%x", &l);
if(l == 0)
break;
printf("\nServer wants to deliver %ld bytes.\n", l);
pfile_chunk = realloc(pfile_chunk, l+1);
memset(pfile_chunk, 0, l);
recv(sock, pfile_chunk, l, 0);
fputs(pfile_chunk, f);
printf("GOT THIS, SIZE %ld:\n%s\n", strlen(pfile_chunk), pfile_chunk);
//get next \r\n bytes.
recv(sock, NULL, 2, 0);
}
最佳答案
至少,您应该检查 recv
的返回值,看看您是否获得了预期的字节数。
在网络上绝对可以进行短读,因为系统调用将在您进行调用时返回套接字接收缓冲区中可用的任何内容。
执行循环直到读入整个 block ,或者将 MSG_WAITALL
标志传递给最后一个参数中的 recv
。但是,您仍然需要从 recv
检查错误。
ssize_t r = recv(sock, pfile_chunk, l, MSG_WAITALL);
if (r < l) {
/* check for errors ... */
} else {
/* got the data */
}
关于C解析HTTP Chunked传输编码响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11621232/