CSocket編程基礎(chǔ)
這是一對實現(xiàn)在兩臺計算機(jī)間傳送文件的函數(shù),我沒有看到過使用CSocket進(jìn)行文件傳送的代碼,希望此代碼對你有用.代碼中包含兩個函數(shù),第一個用于服務(wù)器端,第二個用于客戶端.需要說明的是本文提供的方法并不適用于大型文件的傳送.
下面給出服務(wù)器端代碼:
void SendFile() { #define PORT 34000 /// Select any free port you wish AfxSocketInit(NULL); CSocket sockSrvr; sockSrvr.Create(PORT); // Creates our server socket sockSrvr.Listen(); // Start listening for the client at PORT CSocket sockRecv; sockSrvr.Accept(sockRecv); // Use another CSocket to accept the connection CFile myFile; myFile.Open("C:\\ANYFILE.EXE", CFile::modeRead | CFile::typeBinary); int myFileLength = myFile.GetLength(); // Going to send the correct File Size sockRecv.Send(&myFileLength, 4); // 4 bytes long byte* data = new byte[myFileLength]; myFile.Read(data, myFileLength); sockRecv.Send(data, myFileLength); //Send the whole thing now myFile.Close(); delete data; sockRecv.Close(); }以下是客戶端代碼
void GetFile() { #define PORT 34000 /// Select any free port you wish AfxSocketInit(NULL); CSocket sockClient; sockClient.Create(); // "127.0.0.1" is the IP to your server, same port sockClient.Connect("127.0.0.1", PORT); int dataLength; sockClient.Receive(&dataLength, 4); //Now we get the File Size first byte* data = new byte[dataLength]; sockClient.Receive(data, dataLength); //Get the whole thing CFile destFile("C:\\temp\\ANYFILE.EXE", CFile::modeCreate | CFile::modeWrite | CFile::typeBinary); destFile.Write(data, dataLength); // Write it destFile.Close(); delete data; sockClient.Close();