程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++:使用CSocket進行文件傳送

C++:使用CSocket進行文件傳送

編輯:C++入門知識

有兩個函數,一個用於服務端,用於文件的發送,一個用於客戶端,用於文件的接受,只能進行小文件傳送。

下面給出服務器端發送所用函數代碼:

void SendFile() { #define PORT 34000 /// 自定義端口
AfxSocketInit(NULL);
CSocket sockSrvr;
sockSrvr.Create(PORT); // 創建socket
sockSrvr.Listen(); // 監聽端口
CSocket sockRecv;
sockSrvr.Accept(sockRecv);
CFile myFile; myFile.Open("C:\\test.dat", //發送的文件路徑
CFile::modeRead | CFile::typeBinary);
int myFileLength = myFile.GetLength();
sockRecv.Send(&myFileLength, 4);
byte* data = new byte[myFileLength];
myFile.Read(data, myFileLength);
sockRecv.Send(data, myFileLength);
myFile.Close();
delete data;
sockRecv.Close();
}
以下是客戶端代碼接受所用函數:

void GetFile() { #define PORT 34000 /// 自定義端口
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);
byte* data = new byte[dataLength];
sockClient.Receive(data, dataLength);
CFile destFile("C:\\temp\\test.dat",//保存的文件路徑
CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
destFile.Write(data, dataLength);
destFile.Close();
delete data;
sockClient.Close();
}
最後要注意的是,因為沒有添加判斷代碼,所以確保函數SendFile()先運行,然後再運行GetFile()

 作者“ 李木空間 ”

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved