这是来自http服务器的数据接收功能代码,完美工作..但我想向此功能添加暂停和恢复..
有人可以建议我该怎么做吗??
注意:忽略变量声明。
int rest=0,size=0,count=0;
memset(buffer,'\0',sizeof(buffer));
do {
rc=read(sockfd,buffer,1500); //Reading from socket connection
if(rest==0)
{ /*Extracting Content length*/
data=strstr((char*)buffer,"Content-Length");
if(data!=NULL)
{
value=atoi((char*)data+15);data_rest=value;
rest=1;
}
}
if(count==0)
{ /*Extracting Header*/
content=strstr(buffer,"\r\n\r\n");
if(content!=NULL)
{
printf("FOUND Header END\n");
content=content+4;count=1;
/*copying DATA to the file which has same Extension*/
data_wrote=fwrite(content,sizeof(char),rc-(content-buffer),fp);
}
}
else
{
content=buffer;
/*copying DATA to the file which has same Extension*/
data_wrote=fwrite(content,sizeof(char),rc,fp);
}
size=size+rc;
total_wrote=total_wrote+data_wrote;
printf("Total size = %d\n",size);
memset(buffer,'\0',sizeof(buffer));
} while(rc>0); /*until end of file*/
最佳答案
这是我将使用的过程:
使用
Range: bytes=0-
HTTP/1.1 请求 header 发送初始请求。 如果服务器响应HTTP/1.1 206 Partial content
,您就知道可以稍后恢复连接。 保存ETag
响应 header ,因为除非服务器上的内容发生更改,否则它应该保持不变,和/或Content-Type
和Last-Modified
标题。 请注意,Content-Range
响应 header 指定此响应中字节的偏移量,最终数字是完整内容的总长度,并且仅Content-Length
指定当前响应的长度(不是原始内容的长度)。只需关闭连接即可中断传输。
发送带有
Range: bytes=N-
HTTP/1.1 请求 header 的继续请求,其中N
是到仍缺少的第一个字节的偏移量本地副本。 如果服务器未响应HTTP/1.1 206 Partial content
,您将无法追索,但必须再次下载整个内容(使用正常的 HTTP 请求处理)。 如果ETag
、Content-Type
或Last-Modified
响应 header 不匹配,则内容可能在服务器上被修改,并且您应该断开此连接并下载完整的请求。Content-Range
响应头指定了本次响应中字节的偏移量,最终的数字是完整内容的总长度,而Content-Length
仅指定了当前响应的长度(不是原始内容的长度)。
在所有情况下,服务器都可能使用分块
内容传输编码,因此您也必须做好处理这种情况的准备,因为请求是 HTTP 1.1。请参阅RFC2616了解详情。
当您对此进行测试时,我建议您使用简单的 Bash 脚本来使用自定义 header 连接到某些 URL,并将响应 header 输出到标准错误,将消息内容输出到标准输出:
#!/bin/bash
Host="localhost" # Host name, use your own servers
Port="80"
Query="/" # Path to the content requested
Range="0-" # Byte range requested
# Open up a connection
exec 3<>/dev/tcp/$Host/$Port || exit $?
# Set up a reader sub-shell that will flush the headers
# to standard error, and content to standard out.
( Headers=1
while read Line ; do
Line="${Line//$'\r'/}"
if [ -z "$Line" ]; then
Headers=0
elif [ $Headers -gt 0 ]; then
printf '%s\n' "$Line" >&2
else
printf '%s\n' "$Line"
fi
done
exit 0
) <&3 &
# Construct a byte-range request:
Request=""
Request="$Request""GET $Query HTTP/1.1"$'\r\n'
Request="$Request""Host: $Host"$'\r\n'
Request="$Request""Range: bytes=$Range"$'\r\n'
Request="$Request""Connection: close"$'\r\n'
# Do a normal request.
printf '%s\r\n' "$Request" >&3
# Close the connection (the read end is still open).
exec 3>&-
# and wait for the request to complete.
wait
上面不是 HTTP 客户端,并且不进行分块传输,例如;它只是一个调试工具,您可以使用它来准确查看从服务器流向客户端的数据。
关于有人可以建议我,如何对此数据接收代码实现暂停和恢复功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082418/