发布时间:2021-02-05 来源:未知 浏览量:
作者 Vicken Simonian. 环境:VC6 SP4,NT4 SP5 这里有两个在两台计算机之间传输文件的函数。在我身边并没有看到什么好的CSOCKET文件传输函数,于是我决定帮你写一个。此代码分为Server端和Client端。 Server(发送)端: 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 conne ction CFile myFile; myFile.Open("C:\\ANYFILE.EXE", CFile::modeRead | CFile::typeBinary); int myFileLength = myFile.GetLength(); // Going to send the correct F ile 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(); } Client(接收)端: 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(); delet e data; sockClient.Close(); } (有没有看到,既然能先传文件大小,后传文件,那么仿造这个例子,可以把文件分成多段输)如果再做一个线程,那就更完美了。 在此感谢所有的朋友!Server端必须在Client端之前运行。我相信还有许多可以改进的地方,例如一次传输一个文件,可以将它分成多块(我好像在C版中听某位大虾说过CSocket的Send一次最多只能传64k,不知是对还是错,如不能传则将文件分段)。在任何时候都可以很方便地加入到一个工程中。 |
本站发布的ghost系统仅为个人学习测试使用,请在下载后24小时内删除,不得用于任何商业用途,否则后果自负,请支持购买微软正版软件!
如侵犯到您的权益,请及时通知我们,我们会及时处理。Copyright @ 2018 win10系统下载站(http://www.win10pc.cn) 版权所有 xml地图 邮箱: