WEB开发网
开发学院软件开发VC 点对点多线程断点续传的实现 阅读

点对点多线程断点续传的实现

 2010-01-09 20:31:56 来源:WEB开发网   
核心提示:下面介绍建立各进程函数,很简单:void CMainFrame::createthread(int threadno){DWORD dwthread;//建立BLACK个进程for(int i=0;i<BLACK;i++){m_thread[threadno][i]=::CreateThread(NULL,0,d

下面介绍建立各进程函数,很简单:

void CMainFrame::createthread(int threadno)
{
  DWORD dwthread;
  //建立BLACK个进程
  for(int i=0;i<BLACK;i++)
  {
    m_thread[threadno][i]=  ::CreateThread(NULL,0,downthread,(LPVOID)down [threadno],0,&dwthread);
  }
}

downthread进程函数

DWORD WINAPI downthread(LPVOID lpparam)
{
  cdownload* pthis=(cdownload*)lpparam;
  //进程引索+1
  InterlockedIncrement(&pthis->m_index);
  //执行 下载进程
  pthis->threadfunc(pthis->m_index-1);
  return 1;
}

下面介绍下载进程函数,最最核心的东西了

UINT cdownload::threadfunc(long index)
{
  //初使化联接
  sockaddr_in local;
  SOCKET m_socket;
  int rc=0;

  local.sin_family=AF_INET;
   local.sin_port=htons(1028);
  local.sin_addr.S_un.S_addr=inet_addr(ip);
   m_socket=socket(AF_INET,SOCK_STREAM,0);
  int ret;
  //读入缓存
   char* m_buf=new char[SIZE];
  int re,len2;
  fileinfo fileinfo1;
  // 联接
  ret=connect(m_socket,(LPSOCKADDR)&local,sizeof(local));
  //读入各 进程的下载信息
  fileinfo1.len=filerange[index*2+1];
   fileinfo1.seek=filerange[index*2];
  fileinfo1.type=2;
   fileinfo1.fileno=doinfo.threadno;

  re=fileinfo1.len;

  //打开文 件
  CFile destFile;
  FILE* fp=NULL;
  //是第一次传的话
   if((fp=fopen(fname,"r"))==NULL)
    destFile.Open(fname, CFile::modeCreate|CFile::modeWrite | CFile::typeBinary|CFile::shareDenyNone);
   else
    //如果文件存在,是续传
    destFile.Open(fname,CFile::modeWrite | CFile::typeBinary|CFile::shareDenyNone);
  //文件指针移到指定位置
   destFile.Seek(filerange[index*2],CFile::begin);
  //发消息给服务器,可以传文件了
  sendn(m_socket,(char*)&fileinfo1,100);
  CFile myfile;
  CString temp;
  temp.Format(".down%d",index);
  m_temp=fname+temp;
    //当各段长度还不为0时
  while(re>0){
    len2=re>SIZE?SIZE:re;

    //读各段内容
    int len1=readn(m_socket,m_buf,len2);
     //有错的话
    if(len1<0){
      closesocket(m_socket);
       break;
    }

  //写入文件
  destFile.Write(m_buf, len1);
  //更改记录进度信息
  filerange[index*2+1]-=len1;
  filerange [index*2]+=len1;
  //移动记录文件指针到头
  myfile.Seek(0,CFile::begin);
  //写入记录进度
  myfile.Write(&filerange[index*2],sizeof(int));
   myfile.Write(&filerange[index*2+1],sizeof(int));
  //减去这次读的长度
   re=re-len1;
  //加文件长度
  doinfo.totle=doinfo.totle+len1;
  };

  //这块下载完成,收尾

  myfile.Close();
  destFile.Close ();
  delete [] m_buf;
  shutdown(m_socket,2);

  if (re<=0) good[index]=TRUE;
  return 1;
}

到这客户端的主要模块和机制 已基本介绍完。希望好好体会一下这种多线程断点续传的方法。

上一页  1 2 3 4 5 6 

Tags:线程 断点 实现

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接