CSDN博客

img zzz_781111

Use windows socket to download http page

发表于2008/10/1 17:08:00  1057人阅读

1)Because we need use windows socket to get http page,we need initialise win socket
At the beginning of our application,we should do below:
        int err;
    WORD wVersion;
    WSADATA WSAData;
    wVersion=MAKEWORD(2,0);
    err=WSAStartup(wVersion,&WSAData);
    if(err!=0)
    {
        AfxMessageBox("无法装载Socket库.");
    }
    if(LOBYTE( WSAData.wVersion ) != 2)
    {
        AfxMessageBox("无法找到合适的Socket库.");
        WSACleanup();
    }

After all aplication finished,we should do below:
    WSACleanup();
2)how to download
downLoadHttp.strFileName="c:/1.html";
downLoadHttp.m_strRequest="http://www.baidu.com";
downLoadHttp.Start();
  1. // DownLoadHttp.h: interface for the CDownLoadHttp class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #if !defined(AFX_DOWNLOADHTTP_H__1E0699F1_CFD6_461B_BBF6_44A8A6A4E269__INCLUDED_)
  5. #define AFX_DOWNLOADHTTP_H__1E0699F1_CFD6_461B_BBF6_44A8A6A4E269__INCLUDED_
  6. #if _MSC_VER > 1000
  7. #pragma once
  8. #endif // _MSC_VER > 1000
  9. //
  10. // 单个对象的下载信息
  11. //
  12. typedef struct _downloadcellinfo
  13. {
  14.     int nWillDownloadStartPos;          // 要下载文件的开始位置
  15.     int nWillDownloadSize;              // 本次需要下载的大小,-1表示一直下载到文件尾
  16.     DWORD nDownloadedSize;              // 该线程已下载的大小
  17. } t_DownloadCellInfo;
  18. class CDownLoadHttp  
  19. {
  20. public:
  21.     CDownLoadHttp();
  22.     virtual ~CDownLoadHttp();
  23.     DWORD CDownLoadHttp::GetDownloadElapsedTime();//获取已下载的时间
  24.     CString CDownLoadHttp::FormatFileSize ( double fFileSize );//计算速度
  25.     UINT DownloadThread();              //下载
  26.     void BeginDownLoad(void *pArg);
  27.     void Start();
  28.     void Suspend();
  29.     void Stop2();
  30.     
  31.     CString strFileName;
  32.     CString m_strRequest;
  33.     CHttpSocket HttpSocket;
  34.     HANDLE m_hThread;                               //线程句柄
  35.     t_DownloadCellInfo *m_pDownloadCellInfo;        //下载对象参数
  36.     DWORD m_dwDownloadStartTime;                    //开始时间
  37.     int nCompletedSize ;
  38.     bool bSuspend;
  39.     CFile DownloadFile;
  40. }; 
  41. #endif // !defined(AFX_DOWNLOADHTTP_H__1E0699F1_CFD6_461B_BBF6_44A8A6A4E269__INCLUDED_)
  1. // HttpSocket.cpp: implementation of the CHttpSocket class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "stdafx.h"
  5. #include "HttpSocket.h"
  6. #ifdef _DEBUG
  7. #undef THIS_FILE
  8. static char THIS_FILE[]=__FILE__;
  9. #define new DEBUG_NEW
  10. #endif
  11. #define MAXHEADERSIZE 1024
  12. //////////////////////////////////////////////////////////////////////
  13. // Construction/Destruction
  14. //////////////////////////////////////////////////////////////////////
  15. CHttpSocket::CHttpSocket()
  16. {
  17.     m_s=NULL;
  18.     m_phostent=NULL;
  19.     m_port=80;
  20.     m_bConnected=FALSE;
  21.     for(int i=0;i<256;i++)
  22.         m_ipaddr[i]='/0';
  23.     memset(m_requestheader,0,MAXHEADERSIZE);
  24.     memset(m_ResponseHeader,0,MAXHEADERSIZE);
  25.     m_nCurIndex = 0;        //
  26.     m_bResponsed = FALSE;
  27.     m_nResponseHeaderSize = -1;
  28. /*
  29.     m_nBufferSize = nBufferSize;
  30.     m_pBuffer = new char[nBufferSize];
  31.     memset(m_pBuffer,0,nBufferSize);*/
  32. }
  33. CHttpSocket::~CHttpSocket()
  34. {
  35.     CloseSocket();
  36. }
  37. BOOL CHttpSocket::Socket()
  38. {
  39.     if(m_bConnected)return FALSE;
  40.     struct protoent *ppe; 
  41.     ppe=getprotobyname("tcp"); 
  42.     
  43.     ///创建SOCKET对象
  44.     m_s=socket(PF_INET,SOCK_STREAM,ppe->p_proto);
  45.     if(m_s==INVALID_SOCKET)
  46.     {
  47.         MessageBox(NULL,"socket()函数执行失败!","错误",MB_OK);
  48.         return FALSE;
  49.     }
  50.     return TRUE;
  51. }
  52. BOOL CHttpSocket::Connect(char *szHostName,int nPort)
  53. {
  54.     if(szHostName==NULL)
  55.         return FALSE;
  56.     ///若已经连接,则先关闭
  57.     if(m_bConnected)
  58.     {
  59.         CloseSocket();
  60.     }
  61.     ///保存端口号
  62.     m_port=nPort;
  63.     ///根据主机名获得IP地址
  64.     m_phostent=gethostbyname(szHostName);
  65.     if(m_phostent==NULL)
  66.     {
  67.         MessageBox(NULL,"gethostbyname()函数执行失败!","错误",MB_OK);
  68.         return FALSE;
  69.     }
  70.     
  71.     ///连接
  72.     struct in_addr ip_addr;
  73.     memcpy(&ip_addr,m_phostent->h_addr_list[0],4);///h_addr_list[0]里4个字节,每个字节8位
  74.     
  75.     struct sockaddr_in destaddr;
  76.     memset((void *)&destaddr,0,sizeof(destaddr)); 
  77.     destaddr.sin_family=AF_INET;
  78.     destaddr.sin_port=htons(nPort);
  79.     destaddr.sin_addr=ip_addr;
  80.     ///保存主机的IP地址字符串
  81.     sprintf(m_ipaddr,"%d.%d.%d.%d",
  82.         destaddr.sin_addr.S_un.S_un_b.s_b1,
  83.         destaddr.sin_addr.S_un.S_un_b.s_b2,
  84.         destaddr.sin_addr.S_un.S_un_b.s_b3,
  85.         destaddr.sin_addr.S_un.S_un_b.s_b4);
  86.     /*inet_addr();把带点的IP地址字符串转化为in_addr格式;
  87.       inet_ntoa();作用相反*/
  88.     
  89.     /*注意理解sturct in_addr 的结构:一个32位的数;一共同体的形式使用
  90.     (1)每8位一个即s_b1~s_b4;
  91.     (2)每16位一个即s_w1~s_w2;
  92.     (3)32位s_addr
  93.     struct   in_addr {
  94.     union   {
  95.               struct{
  96.                 unsigned  char   s_b1,
  97.                                  s_b2,
  98.                                  s_b3,
  99.                                  s_b4;
  100.                     } S_un_b;
  101.               struct{
  102.                 unsigned  short  s_w1,
  103.                                  s_w2
  104.                     }S_un_w;      
  105.                unsigned long  S_addr;
  106.             } S_un;
  107.         };
  108.     */
  109.     if(connect(m_s,(struct sockaddr*)&destaddr,sizeof(destaddr))!=0)
  110.     {
  111.         //CloseSocket();
  112.         //m_s=NULL;
  113.         MessageBox(NULL,"connect()函数执行失败!","错误",MB_OK);
  114.         return FALSE;
  115.     }
  116.     ///设置已经连接的标志
  117.     m_bConnected=TRUE;
  118.     return TRUE;
  119. }
  120. ///根据请求的相对URL输出HTTP请求头
  121. const char *CHttpSocket::FormatRequestHeader(char *pServer,char *pObject, long &Length,
  122.                                       char *pCookie,char *pReferer,long nFrom,
  123.                                       long nTo,int nServerType)
  124. {
  125.     char szPort[10];
  126.     char szTemp[20];
  127.     sprintf(szPort,"%d",m_port);
  128.     memset(m_requestheader,'/0',1024);
  129.     ///第1行:方法,请求的路径,版本
  130.     strcat(m_requestheader,"GET ");
  131.     strcat(m_requestheader,pObject);
  132.     strcat(m_requestheader," HTTP/1.1");
  133.     strcat(m_requestheader,"/r/n");
  134.     ///第2行:主机
  135.     strcat(m_requestheader,"Host:");
  136.     strcat(m_requestheader,pServer);
  137.     strcat(m_requestheader,"/r/n");
  138.     ///第3行:
  139.     if(pReferer != NULL)
  140.     {
  141.         strcat(m_requestheader,"Referer:");
  142.         strcat(m_requestheader,pReferer);
  143.         strcat(m_requestheader,"/r/n");     
  144.     }
  145.     ///第4行:接收的数据类型
  146.     strcat(m_requestheader,"Accept:*/*");
  147.     strcat(m_requestheader,"/r/n");
  148.     ///第5行:浏览器类型
  149.     strcat(m_requestheader,"User-Agent:Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)");
  150.     strcat(m_requestheader,"/r/n");
  151.     ///第6行:连接设置,保持
  152.     strcat(m_requestheader,"Connection:Keep-Alive");
  153.     strcat(m_requestheader,"/r/n");
  154.     ///第7行:Cookie.
  155.     if(pCookie != NULL)
  156.     {
  157.         strcat(m_requestheader,"Set Cookie:0");
  158.         strcat(m_requestheader,pCookie);
  159.         strcat(m_requestheader,"/r/n");
  160.     }
  161.     ///第8行:请求的数据起始字节位置(断点续传的关键)
  162.     if(nFrom > 0)
  163.     {
  164.         strcat(m_requestheader,"Range: bytes=");
  165.         _ltoa(nFrom,szTemp,10);
  166.         strcat(m_requestheader,szTemp);
  167.         strcat(m_requestheader,"-");
  168.         if(nTo > nFrom)
  169.         {
  170.             _ltoa(nTo,szTemp,10);
  171.             strcat(m_requestheader,szTemp);
  172.         }
  173.         strcat(m_requestheader,"/r/n");
  174.     }
  175.     
  176.     ///最后一行:空行
  177.     strcat(m_requestheader,"/r/n");
  178.     ///返回结果
  179.     Length=strlen(m_requestheader);
  180.     return m_requestheader;
  181. }
  182. ///发送请求头
  183. BOOL CHttpSocket::SendRequest(const char *pRequestHeader, long Length)
  184. {
  185.     if(!m_bConnected)return FALSE;
  186.     if(pRequestHeader==NULL)
  187.         pRequestHeader=m_requestheader;
  188.     if(Length==0)
  189.         Length=strlen(m_requestheader);
  190.     if(send(m_s,pRequestHeader,Length,0)==SOCKET_ERROR)
  191.     {
  192.         MessageBox(NULL,"send()函数执行失败!","错误",MB_OK);
  193.         return FALSE;
  194.     }
  195.     int nLength;
  196.     GetResponseHeader(nLength);
  197.     return TRUE;
  198. }
  199. long CHttpSocket::Receive(char* pBuffer,long nMaxLength)
  200. {
  201.     if(!m_bConnected)return NULL;
  202.     ///接收数据
  203.     long nLength;
  204.     nLength=recv(m_s,pBuffer,nMaxLength,0);
  205.     
  206.     if(nLength <= 0)
  207.     {
  208.         //MessageBox(NULL,"recv()函数执行失败!","错误",MB_OK);
  209.         CloseSocket();
  210.     }
  211.     return nLength;
  212. }
  213. ///关闭套接字
  214. BOOL CHttpSocket::CloseSocket()
  215. {
  216.     if(m_s != NULL)
  217.     {
  218.         if(closesocket(m_s)==SOCKET_ERROR)
  219.         {
  220.             MessageBox(NULL,"closesocket()函数执行失败!","错误",MB_OK);
  221.             return FALSE;
  222.         }
  223.     }
  224.     m_s = NULL;
  225.     m_bConnected=FALSE;
  226.     return TRUE;
  227. }
  228. int CHttpSocket::GetRequestHeader(char *pHeader, int nMaxLength) const
  229. {
  230.     int nLength;
  231.     if(int(strlen(m_requestheader))>nMaxLength)
  232.     {
  233.         nLength=nMaxLength;
  234.     }
  235.     else
  236.     {
  237.         nLength=strlen(m_requestheader);
  238.     }
  239.     memcpy(pHeader,m_requestheader,nLength);
  240.     return nLength;
  241. }
  242. //设置接收或者发送的最长时间
  243. BOOL CHttpSocket::SetTimeout(int nTime, int nType)
  244. {
  245.     if(nType == 0)
  246.     {
  247.         nType = SO_RCVTIMEO;
  248.     }
  249.     else
  250.     {
  251.         nType = SO_SNDTIMEO;
  252.     }
  253.     DWORD dwErr;
  254.     dwErr=setsockopt(m_s,SOL_SOCKET,nType,(char*)&nTime,sizeof(nTime)); 
  255.     if(dwErr)
  256.     {
  257.         MessageBox(NULL,"setsockopt()函数执行失败!","错误",MB_OK);
  258.         return FALSE;
  259.     }
  260.     return TRUE;
  261. }
  262. //获取HTTP请求的返回头
  263. const char* CHttpSocket::GetResponseHeader(int &nLength)
  264. {
  265. //  if(!m_bResponsed)
  266.     {
  267.         char c = 0;
  268.         int nIndex = 0;
  269.         m_nResponseHeaderSize=-1;
  270.         BOOL bEndResponse = FALSE;
  271.         while(!bEndResponse && nIndex < MAXHEADERSIZE)
  272.         {
  273.             recv(m_s,&c,1,0);
  274.             m_ResponseHeader[nIndex++] = c;
  275.             if(nIndex >= 4)
  276.             {
  277.                 if(m_ResponseHeader[0]!='H'&&m_ResponseHeader[1]!='T'
  278.                     &&m_ResponseHeader[2]!='T'&&m_ResponseHeader[3]!='P')
  279.                 {
  280.                     AfxMessageBox("返回信息有误,下载中止");
  281.                     CloseSocket();
  282.                     break;
  283.                 }
  284.                 if(m_ResponseHeader[nIndex - 4] == '/r' && m_ResponseHeader[nIndex - 3] == '/n'
  285.                     && m_ResponseHeader[nIndex - 2] == '/r' && m_ResponseHeader[nIndex - 1] == '/n')
  286.                 bEndResponse = TRUE;
  287.             }
  288.         }
  289.         
  290.         m_nResponseHeaderSize = nIndex;
  291.         m_ResponseHeader[nIndex]=NULL;
  292.         m_bResponsed = TRUE;
  293.     }
  294.     
  295.     nLength = m_nResponseHeaderSize;
  296.     return m_ResponseHeader;
  297. }
  298. //返回HTTP响应头中的一行.
  299. int CHttpSocket::GetResponseLine(char *pLine, int nMaxLength)
  300. {
  301.     if(m_nCurIndex >= m_nResponseHeaderSize)
  302.     {
  303.         m_nCurIndex = 0;
  304.         return -1;
  305.     }
  306.     int nIndex = 0;
  307.     char c = 0;
  308.     do 
  309.     {
  310.         c = m_ResponseHeader[m_nCurIndex++];
  311.         pLine[nIndex++] = c;
  312.     } while(c != '/n' && m_nCurIndex < m_nResponseHeaderSize && nIndex < nMaxLength);
  313.     
  314.     return nIndex;
  315. }
  316. int CHttpSocket::GetField(const char *szSession, char *szValue, int nMaxLength)
  317. {
  318.     //取得某个域值
  319.     if(!m_bResponsed) return -1;
  320.     
  321.     CString strRespons;
  322.     strRespons = m_ResponseHeader;
  323.     int nPos = -1;
  324.     nPos = strRespons.Find(szSession,0);
  325.     if(nPos != -1)
  326.     {
  327.         nPos += strlen(szSession);
  328.         nPos += 2;
  329.         int nCr = strRespons.Find("/r/n",nPos);
  330.         CString strValue = strRespons.Mid(nPos,nCr - nPos);
  331.         strcpy(szValue,strValue);
  332.         return (nCr - nPos);
  333.     }
  334.     else
  335.     {
  336.         return -1;
  337.     }
  338. }
  339. int CHttpSocket::GetServerState()
  340. {
  341.     //若没有取得响应头,返回失败
  342.     if(!m_bResponsed) return -1;
  343.     
  344.     char szState[3];
  345.     szState[0] = m_ResponseHeader[9];
  346.     szState[1] = m_ResponseHeader[10];
  347.     szState[2] = m_ResponseHeader[11];
  348.     return atoi(szState);
  349. }
  1. // HttpSocket.h: interface for the CHttpSocket class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #if !defined(AFX_HTTPSOCKET_H__F49A8F82_A933_41A8_AF47_68FBCAC4ADA6__INCLUDED_)
  5. #define AFX_HTTPSOCKET_H__F49A8F82_A933_41A8_AF47_68FBCAC4ADA6__INCLUDED_
  6. #include "winsock2.h"
  7. #include <afxinet.h>
  8. #include <afxsock.h>
  9. #if _MSC_VER > 1000
  10. #pragma once
  11. #endif // _MSC_VER > 1000
  12. class _declspec(dllexport) CHttpSocket  :public CSocket
  13. {
  14. public:
  15.     int             GetServerState();                       //返回服务器状态码 -1表示不成功
  16.     int             GetField(const char* szSession,char *szValue,int nMaxLength);   //返回某个域值,-1表示不成功
  17.     int             GetResponseLine(char *pLine,int nMaxLength);                //获取返回头的一行
  18.     const char*     GetResponseHeader(int &Length);                             //获取完整的返回头
  19.     const char *    FormatRequestHeader(char *pServer,char *pObject,long &Length,
  20.                         char* pCookie=NULL,char *pReferer=NULL,
  21.                         long nFrom=0,long nTo=0,
  22.                         int nServerType=0);                                 //格式化请求头
  23.     int             GetRequestHeader(char *pHeader,int nMaxLength) const;
  24.     BOOL            SendRequest(const char* pRequestHeader = NULL,long Length = 0);
  25.     
  26.     CHttpSocket();
  27.     virtual ~CHttpSocket();
  28.     BOOL            SetTimeout(int nTime,int nType=0);
  29.     long            Receive(char* pBuffer,long nMaxLength);
  30.     BOOL            Connect(char* szHostName,int nPort=80);
  31.     BOOL            Socket();
  32.     BOOL            CloseSocket();
  33.     char m_ResponseHeader[1024];    //回应头
  34. protected:  
  35.     char m_requestheader[1024];     //请求头
  36.     int m_port;                     //端口
  37.     char m_ipaddr[256];             //IP地址
  38.     BOOL m_bConnected;
  39.     SOCKET m_s;
  40.     hostent *m_phostent;
  41.     int m_nCurIndex;                //GetResponsLine()函数的游标记录
  42.     BOOL m_bResponsed;              //是否已经取得了返回头
  43.     int m_nResponseHeaderSize;      //回应头的大小
  44. /*
  45.     int m_nBufferSize;
  46.     char *m_pBuffer;*/
  47. };
  48. #endif // !defined(AFX_HTTPSOCKET_H__F49A8F82_A933_41A8_AF47_68FBCAC4ADA6__INCLUDED_)

  1. // DownLoadHttp.cpp: implementation of the CDownLoadHttp class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "stdafx.h"
  5. #include "HttpSocket.h"
  6. #include "DownLoadHttp.h"
  7. //#include "TestHttpDlg.h"
  8. #ifdef _DEBUG
  9. #undef THIS_FILE
  10. static char THIS_FILE[]=__FILE__;
  11. #define new DEBUG_NEW
  12. #endif
  13. //////////////////////////////////////////////////////////////////////
  14. // Construction/Destruction
  15. //////////////////////////////////////////////////////////////////////
  16.  
  17. CDownLoadHttp::CDownLoadHttp()
  18. {
  19.     nCompletedSize=0;
  20.         m_hThread = NULL;
  21.         bSuspend=false
  22. }
  23. CDownLoadHttp::~CDownLoadHttp()
  24. {
  25. }
  26. //
  27. // 获取下载所消耗的时间(毫秒),可用来计算下载速度和推算剩余时间
  28. //
  29. DWORD CDownLoadHttp::GetDownloadElapsedTime()
  30. {
  31.     return (GetTickCount() - m_dwDownloadStartTime);
  32. }
  33. UINT CDownLoadHttp::DownloadThread()
  34.  
  35.     
  36.     CString strServer,strObject;
  37.     unsigned short nPort;
  38.     DWORD dwServiceType;
  39.     long nLength;
  40. //  char  pCookie[256]='/0';
  41. //  char  pReferer[256]='/0';
  42.     const char *pRequestHeader = NULL;
  43.     
  44.     BOOL bIsTran=TRUE;
  45.     int nSvrState;
  46.     while(bIsTran)
  47.     {
  48.         
  49.         
  50.         AfxParseURL(m_strRequest,dwServiceType,strServer,strObject,nPort);
  51.         pRequestHeader = HttpSocket.FormatRequestHeader((LPTSTR)(LPCTSTR)strServer
  52.             ,(LPTSTR)(LPCTSTR)strObject,nLength,NULL,NULL,nCompletedSize);  
  53.         
  54.          
  55.         HttpSocket.Socket();
  56.         HttpSocket.Connect((LPTSTR)(LPCTSTR)strServer,nPort);
  57.         HttpSocket.SendRequest();
  58.         HttpSocket.SetTimeout(10000,0); 
  59.     //  HttpSocket.GetField("Cookie",pCookie,256);
  60.         
  61.         //服务器状态,(300,400)被重定向
  62.         nSvrState = HttpSocket.GetServerState();
  63.         if( nSvrState>= 300 && nSvrState< 400 )
  64.         {
  65.             char sLocal[256];
  66.             int path=HttpSocket.GetField("Location",sLocal,256);
  67.          
  68.             bIsTran=TRUE;
  69.             HttpSocket.CloseSocket();       
  70.         }
  71.         else bIsTran=FALSE;
  72.     }
  73.     
  74.     if(nSvrState<200||nSvrState>=400)
  75.     {
  76.         AfxMessageBox("服务器信息有错");
  77.         return 0;
  78.     }
  79.     BeginDownLoad(NULL);
  80.     
  81.     return 0;
  82. }
  83. void CDownLoadHttp::BeginDownLoad(void *pArg)
  84.     char szValue[30];
  85.     HttpSocket.GetField("Content-Length",szValue,30);
  86.     int nFileSize = atoi(szValue);  
  87.     
  88.     int iThisDown=0;
  89.     DownloadFile.Open(strFileName,CFile::modeCreate | CFile::modeReadWrite|CFile::modeNoTruncate|CFile::shareDenyNone);
  90.     long lposition=DownloadFile.GetPosition();
  91.     long fileLength=DownloadFile.GetLength();
  92.     if(nCompletedSize)lposition=DownloadFile.Seek(nCompletedSize,CFile::begin);
  93.     char pData[1024];
  94.     int nReceSize = 0;
  95.     m_dwDownloadStartTime= GetTickCount();
  96.     while(iThisDown< nFileSize)
  97.     {
  98.     
  99.     
  100.         nReceSize = HttpSocket.Receive(pData,1024);
  101.         if(nReceSize == 0)
  102.         {
  103.             AfxMessageBox("服务器已经关闭连接.");
  104.         //  DownloadFile.Close();
  105.             break;
  106.         }
  107.         if(nReceSize == -1)
  108.         {
  109.             AfxMessageBox("接收数据超时.");
  110.     //      DownloadFile.Close();
  111.             break;
  112.         }
  113.     
  114.         DownloadFile.Write(pData,nReceSize);
  115.         iThisDown+=nReceSize;
  116.         nCompletedSize += nReceSize; 
  117.         
  118.         //Speed
  119.         int nElapsedTime = this->GetDownloadElapsedTime ();
  120.         if ( nElapsedTime > 5*1000 || ( nElapsedTime > 2*1000 && nCompletedSize > 1024*10 ) )
  121.         {
  122.             double dSpeed = (double)nCompletedSize / ((double)nElapsedTime / 1000.0);
  123.             CString csSpeed = FormatFileSize ( dSpeed );
  124.             csSpeed += "/S"
  125.         }
  126.     
  127.     }
  128.     if(iThisDown==nFileSize)
  129.     {
  130.         AfxMessageBox("Download Complete");
  131.     }
  132.         HttpSocket.CloseSocket(); 
  133.         ::CloseHandle ( m_hThread );
  134.         (m_hThread) = NULL;
  135.     
  136.         DownloadFile.Close();
  137.             
  138.     
  139.     
  140.     
  141.     
  142. }
  143. CString CDownLoadHttp::FormatFileSize ( double fFileSize )
  144. {
  145.     CString csRet;
  146.     if ( fFileSize < 1024.0 )
  147.     {
  148.         csRet.Format ( "%d b", fFileSize );
  149.     }
  150.     else if ( fFileSize >= 1024.0 && fFileSize < 1024.0*1024.0 )
  151.     {
  152.         csRet.Format ( "%.2f K", fFileSize/1024.0 );
  153.     }
  154.     else if ( fFileSize >= 1024.0*1024.0 && fFileSize < 1024.0*1024.0*1024.0 )
  155.     {
  156.         csRet.Format ( "%.2f M", fFileSize/(1024.0*1024.0) );
  157.     }
  158.     else
  159.     {
  160.         csRet.Format ( "%.2f G", fFileSize/(1024.0*1024.0*1024.0) );
  161.     }
  162.     return csRet;
  163. }
  164. DWORD WINAPI  DownloadThread(void *pArg)
  165. {
  166.      CDownLoadHttp *nDownLoad=(CDownLoadHttp *)pArg;
  167.      nDownLoad->DownloadThread();
  168.      return 0;
  169.     
  170. }
  171. void CDownLoadHttp::Start()
  172. {
  173.     DWORD dwThreadId=0;
  174.     m_hThread = CreateThread ( NULL, 0, ::DownloadThread, LPVOID(this), 0, &dwThreadId );
  175.     if ( !m_hThread )
  176.     {
  177.         AfxMessageBox("Create download thread failed" );
  178.     
  179.     }
  180. }
  181. void CDownLoadHttp::Suspend()
  182. {
  183.     
  184.     if ( m_hThread )
  185.     {
  186. /*      //  HttpSocket.CancelBlockingCall ();
  187.             HttpSocket.CloseSocket(); 
  188.         DWORD dwWaitTime=5000;
  189.         if ( ::WaitForSingleObject ( m_hThread, dwWaitTime ) == WAIT_TIMEOUT )
  190.         {
  191.             ::TerminateThread ( m_hThread, 0 );
  192.         }
  193.         ::CloseHandle ( m_hThread );
  194.         (m_hThread) = NULL;
  195.         
  196.         */      
  197.         if(!bSuspend)
  198.         {
  199.             
  200.             SuspendThread(m_hThread);
  201.             bSuspend=true;
  202.             CString sSuspend;
  203.             sSuspend.Format("Suspend %d",this->nCompletedSize);
  204.             
  205.             AfxMessageBox(sSuspend);
  206.         }
  207.         else
  208.         {
  209.     //      AfxMessageBox("Resume");
  210.             CString sResume;    
  211.             sResume.Format("Resume  %d",this->nCompletedSize);
  212.             AfxMessageBox(sResume);
  213.             ResumeThread(m_hThread);
  214.             bSuspend=false;
  215.             
  216.         }
  217.         
  218.     }
  219.     else    AfxMessageBox("Please download first.");    
  220. }
  221. void CDownLoadHttp::Stop2()
  222. {
  223.     
  224.     if ( m_hThread )
  225.     {
  226.     
  227.         //  HttpSocket.CancelBlockingCall ();
  228.         SuspendThread(m_hThread);
  229.         HttpSocket.CloseSocket(); 
  230.         DWORD dwWaitTime=500;
  231.         if ( ::WaitForSingleObject ( m_hThread, dwWaitTime ) == WAIT_TIMEOUT )
  232.         {
  233.             ::TerminateThread ( m_hThread, 0 );
  234.         }
  235.         ::CloseHandle ( m_hThread );
  236.         (m_hThread) = NULL;
  237.     
  238.         DownloadFile.Close();
  239.                 
  240.     }
  241. }

0 0

相关博文

我的热门文章

img
取 消
img