使用CSockets进行文件传送

这是一对实现在两台计算机间传送文件的函数,我没有看到过使用CSocket进行文件传送的代码,希望此代码对你有用.代码中包含两个函数,第一个用于服务器端,第二个用于客户端.
需要说明的是本文提供的方法并不适用于大型文件的传送.

下面给出服务器端代码:

 1  void  SendFile()
 2  {
 3    #define  PORT 34000  // / Select any free port you wish
 4 
 5   AfxSocketInit(NULL);
 6   CSocket sockSrvr; 
 7   sockSrvr.Create(PORT);  //  Creates our server socket
 8   sockSrvr.Listen();  //  Start listening for the client at PORT
 9   CSocket sockRecv;
10   sockSrvr.Accept(sockRecv);  //  Use another CSocket to accept the connection
11 
12 
13   CFile myFile;
14   myFile.Open( " C:\\ANYFILE.EXE " , CFile::modeRead  |  CFile::typeBinary); 
15 
16    int  myFileLength  =  myFile.GetLength();  //  Going to send the correct File Size
17 
18   sockRecv.Send( & myFileLength,  4 );  //  4 bytes long
19          
20    byte *  data  =   new   byte [myFileLength]; 
21 
22   myFile.Read(data, myFileLength);
23 
24   sockRecv.Send(data, myFileLength);  // Send the whole thing now
25 
26   myFile.Close();
27   delete data;
28 
29   sockRecv.Close();
30  }
31 

 

以下是客户端代码

 

 1  void  GetFile()
 2  {
 3    #define  PORT 34000  // / Select any free port you wish
 4 
 5   AfxSocketInit(NULL);
 6   CSocket sockClient;
 7   sockClient.Create();
 8 
 9    //  "127.0.0.1" is the IP to your server, same port
10   sockClient.Connect( " 127.0.0.1 " , PORT); 
11 
12    int  dataLength;
13   sockClient.Receive( & dataLength,  4 );  // Now we get the File Size first
14          
15    byte *  data  =   new   byte [dataLength];
16   sockClient.Receive(data, dataLength);  // Get the whole thing
17 
18   CFile destFile( " C:\\temp\\ANYFILE.EXE "
19    CFile::modeCreate  |  CFile::modeWrite  |  CFile::typeBinary);
20 
21   destFile.Write(data, dataLength);  //  Write it
22 
23   destFile.Close();
24 
25   delete data;
26   sockClient.Close();
27  }
28 


你可能感兴趣的:(socket)