| 使用http协议和winsockapi实现webzip文件下载 |
| 当前位置: 论文资料 >> 计算机论文 >> 计算机应用 >> 使用http协议和winsockapi实现webzip文件下载 | ||
| 使用http协议和winsockapi实现webzip文件下载 | ||||
|
mysocket:tsocket; myclient:tsockaddr; recvbuf:array [0..332] of char; mycmdstr:string; ptemp:pchar; myhandle,index_ch,reccount,i:integer; begin //创建本地socket mysocket:=socket(af_inet,sock_stream,0); if (mysocket=socket_error) then begin application.messagebox(′初始化失败!′,′信息′,mb_ok); exit; end; //生成连接主机的结构 myclient.sin_family:=af_inet; myclient.sin_port:=htons(connectedport); // connectedport:全局变量,记录连接端口号 strpcopy(recvbuf,getserverip(fileurl)); // getserverip(fileurl):返回服务器的ip myclient.sin_addr.s_addr:=inet_addr(recvbuf); //连接服务器 if (connect(mysocket,myclient,sizeof(myclient))〈〉0) then begin closesocket(mysocket); exit; end; //发请求 if (q_useproxy=0) then mycmdstr:=′get ′+extracturlpath(fileurl)+′ http/1.1′ //extracturlpath(fileurl)返回相对url else mycmdstr:=′get ′+fileurl+′ http/1.1′;//使用代理写全url strpcopy(recvbuf,mycmdstr); i:=length(mycmdstr); recvbuf[i]:=#13; inc(i); recvbuf[i]:=#10; inc(i); recvbuf[i]:=#13; inc(i); recvbuf[i]:=#10; inc(i); recvbuf[i]:=#0; send(mysocket,recvbuf,i,0); //发送请求读返回数据 reccount:=recv(mysocket,recvbuf,sizeof(recvbuf)-1,0); //判断是否成功 i:=0; while i〈10 do begin i:=i+1; // ′http/1.0 200 ok′是成功标志 if ((recvbuf[i]=′ ′) and (recvbuf[i+1]=′2′) and (recvbuf[i+2]=′0′) and (recvbuf[i+3]=′0′) and (recvbuf[i+4]=′ ′)) then i:=200; end; if i〈〉200 then begin closesocket(mysocket); exit; end; //得到数据起始位置 ptemp:=strpos(recvbuf,#13+#10+#13+#10)+4; index_ch:=ptemp-recvbuf; //建立下载目录 try forcedirectories(extractfilepath(getfillocalpath(fileurl))); except end; //创建文件 deletefile(getfillocalpath(fileurl)); myhandle:=filecreate(getfillocalpath(fileurl)); //如果未接收完则继续 while (reccount〈〉0) do begin filewrite(myhandle,recvbuf[index_ch] ,reccount-(index_ch)); index_ch:=0; reccount:=recv(mysocket,recvbuf,sizeof(recvbuf)-1,0); end; //关闭文件句柄和套接字 fileclose(myhandle); closesocket(mysocket); end; |
||||
|
|
||||