E K*_*ski 4 c http transfer-encoding chunked-encoding http-chunked
我正在开发一个需要解析Chunked类型HTTP传输的客户端.我试着用下面的方法弄清楚错误,并且如果有人能够更快地捕捉到我的错误,我会很感激.总结一下这个问题:似乎客户端没有收到所有的块,从而搞砸了剩下的进程.提前致谢!
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);
}
Run Code Online (Sandbox Code Playgroud)
至少,您应该检查返回值,recv以查看是否获得了您希望获得的字节数.
网络上肯定可以进行简短的读取,因为系统调用将在您进行呼叫时返回套接字接收缓冲区中可用的任何内容.
实现循环,直到读入整个块,或将MSG_WAITALL标志传递给recv最后一个参数.但是,您仍需要检查错误recv.
ssize_t r = recv(sock, pfile_chunk, l, MSG_WAITALL);
if (r < l) {
/* check for errors ... */
} else {
/* got the data */
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3708 次 |
| 最近记录: |