VC++中使用Socket网络 文件传输 结构

1.SOCKET_STREAM_FILE_INFO格式:

typedef struct _SOCKET_STREAM_FILE_INFO {
  
   TCHAR szFileTitle[128]; //文件的标题名
   DWORD dwFileAttributes; //文件的属性
   FILETIME ftCreationTime; //文件的创建时间
   FILETIME ftLastAccessTime; //文件的最后访问时间
   FILETIME ftLastWriteTime; //文件的最后修改时间
   DWORD nFileSizeHigh; //文件大小的高位双字
   DWORD nFileSizeLow; //文件大小的低位双字
   DWORD dwReserved0; //保留,为0
   DWORD dwReserved1; //保留,为0
  
  } SOCKET_STREAM_FILE_INFO, * PSOCKET_STREAM_FILE_INFO;

2.文件发送:
   CFile myFile;

        ‍if(!myFile.Open(fileneme, CFile::modeRead | CFile::typeBinary))
   {
   AfxMessageBox("文件不存在!",MB_OK|MB_ICONERROR);
   return;
   }
   CSocket sockSrvr;
   sockSrvr.Create(800);
  
   sockSrvr.Listen();
   CSocket sockRecv;
   sockSrvr.Accept(sockRecv);
  
   SOCKET_STREAM_FILE_INFO StreamFileInfo;
   WIN32_FIND_DATA FindFileData;
  
   FindClose(FindFirstFile(filename,FindFileData));
   memset(&StreamFileInfo,0,sizeof(SOCKET_STREAM_FILE_INFO));
   strcpy(StreamFileInfo.szFileTitle,myFile.GetFileTitle());
  
   StreamFileInfo.dwFileAttributes = FindFileData.dwFileAttributes;
   StreamFileInfo.ftCreationTime = FindFileData.ftCreationTime;
   StreamFileInfo.ftLastAccessTime = FindFileData.ftLastAccessTime;
   StreamFileInfo.ftLastWriteTime = FindFileData.ftLastWriteTime;
   StreamFileInfo.nFileSizeHigh = FindFileData.nFileSizeHigh;
   StreamFileInfo.nFileSizeLow = FindFileData.nFileSizeLow;
  
   sockRecv.Send(&StreamFileInfo,sizeof(SOCKET_STREAM_FILE_INFO));
  
   UINT dwRead=0;
   while(dwRead
   {
   byte* data = new byte[1024];
   UINT dw=myFile.Read(data, 1024);
   sockRecv.Send(data, dw);
   dwRead+=dw;
   }
   myFile.Close();
   sockRecv.Close();
   AfxMessageBox("发送完毕!");

3. 接受文件

     CSocket sockClient;
  sockClient.Create();
  if(!sockClient.Connect((LPCTSTR)szIP, 800))
  {
  AfxMessageBox("连接到对方机器失败!");
  return;
  }
  SOCKET_STREAM_FILE_INFO StreamFileInfo;
  sockClient.Receive(&StreamFileInfo,sizeof(SOCKET_STREAM_FILE_INFO));
  CFile destFile(StreamFileInfo.szFileTitle, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
 
  UINT dwRead = 0;
  while(dwRead
  {
  byte* data = new byte[1024];
  memset(data,0,1024);
 
  UINT dw=sockClient.Receive(data, 1024);
  destFile.Write(data, dw);
 
  dwRead+=dw;
  }
 
  SetFileTime((HANDLE)destFile.m_hFile,&StreamFileInfo.ftCreationTime,
  &StreamFileInfo.ftLastAccessTime,&StreamFileInfo.ftLastWriteTime);
  destFile.Close();
  SetFileAttributes(StreamFileInfo.szFileTitle,StreamFileInfo.dwFileAttributes);
  sockClient.Close();
  AfxMessageBox("接收完毕!");

posted @ 2010-12-03 22:45  BuildNewApp  阅读(2987)  评论(0编辑  收藏  举报