Chinaunix首页 | 论坛 | 博客
  • 博客访问: 54158
  • 博文数量: 13
  • 博客积分: 1455
  • 博客等级: 上尉
  • 技术积分: 150
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-09 09:53
文章分类

全部博文(13)

文章存档

2012年(1)

2011年(2)

2010年(10)

我的朋友

分类: C/C++

2010-11-16 21:47:21

关于文件操作API方法以前用过,这次用了下MFC封装好的CFILE类实现文件的传输,这对大的双机文件传输来说还是蛮方便的。这种方法可以传输文本文件和二进制文件都可以.
 
CSOCKT建立连接比较容易,如下
CSocket sockClient;
void CFileTrans::MakeConnection(string address,int port)
{
 AfxSocketInit(NULL);
 sockClient.Create();
 sockClient.Connect(address.c_str(), port);
}
 
发送端获取待传输文件的大小,发送到接收端,接收端根据发送的大小申请空间,准备接受文件,这里一定要注意申请的内存空间的大小不能太大,因为内存正常情况下可以申请的内存大小最好不要大于1G,所以这里每次限制申请空间的大小最大为1k,分情况来传输接收。
 
 
 
接受端:(sockClient需要先建立连接)
void CFileTrans::RecvFile(string fileName)

int myFileLength;
sockClient.Receive(&myFileLength, sizeof(myFileLength));  
 
CFile destFile(fileName.c_str(),CFile::modeCreate | CFile::modeWrite);

 if (myFileLength<1024)
 {
  byte* data = new byte[myFileLength];
  if (data==NULL)
  {
   AfxMessageBox("文件长度小于1024内存不足");
   exit(0);
  }
  sockClient.Receive(data, myFileLength); //Get the whole thing
  destFile.Write(data, myFileLength); // Write it
  delete []data;
 }
 else
 {
  
  for (int i=0; i  {
   byte* data = new byte[1024];
   if (data==NULL)
   {
    AfxMessageBox("文件长度大于1024,整数中内存不足");
    exit(0);
   }
   sockClient.Receive(data, 1024); //Get the whole thing
   destFile.Write(data, 1024); // Write it
   delete [] data;
  }
  if (myFileLength%1024!=0)
  {
   int len=myFileLength-i*1024;
   byte* data=new byte[len];
   if (data==NULL)
   {
    AfxMessageBox("文件大小大于1024,之外内存不足");
    exit(0);
   }
   sockClient.Receive(data, len); //Get the whole thing
   destFile.Write(data, len); // Write it
   delete []data;
  }
 }
 destFile.Close();
}
 
发送端:
 CFile myFile;
 myFile.Open(fileName.c_str(), CFile::modeRead);
 int myFileLength = myFile.GetLength(); // Going to send the correct File Size
 sockClient.Send(&myFileLength, sizeof(myFileLength)); // 4 bytes long
 byte* data;
 if (myFileLength<1024)
 {
  data = new byte[myFileLength];
  if (data==NULL)
  {
   AfxMessageBox("内存不足");
   exit(0);
  }
  myFile.Read(data, myFileLength);
  sockClient.Send(data, myFileLength); //Send the whole thing now
  delete []data;
 }
 else
 {
  for (int i=0; i  {
   data = new byte[1024];
   if (data==NULL)
   {
    AfxMessageBox("内存不足");
    exit(0);
   }
   myFile.Read(data, 1024);
   sockClient.Send(data, 1024); //Send the whole thing now
   delete []data;
  }
  if (myFileLength/1024!=0)
  {
   int len=myFileLength-i*1024;
   data=new byte[len];
   if (data==NULL)
   {
    AfxMessageBox("内存不足");
    exit(0);
   }
   myFile.Read(data, len);
   sockClient.Send(data, len); //Send the whole thing now
   delete []data;
  }
 }
 myFile.Close();
 
}
阅读(1301) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-11-17 16:43:08

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com