CSOCKET文件传输函数

本文介绍了一个使用CSOCKET在客户端与服务器之间传输文件的方法。通过发送文件大小信息后传输文件内容,实现了可靠的数据传输。该方法适用于VC6 SP4环境下,能在两台计算机间稳定传输文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CSOCKET文件传输函数


作者:dkink

小生在CODEGURN上发现了一篇文章,觉得还可以,就推荐给大家
此文章的作者为:Vicken Simonian.
环境:VC6 SP4,NT4 SP5
这里有两个在两台计算机之间传输文件的函数。在我身边并没有看到什么好的CS
OCKET文件传输函数,
于是我决定帮你写一个。此代码分为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版中听某位大虾说过CSoc
ket的Send
一次最多只能传64k,不知是对还是错,如不能传则将文件分段)。在任何时候都
可以很方
便地加入到一个工程中。

日期:2000年1月3日
来源:http://www.codeguru.com/network/FileTransferUsingSockets.shtml

注释:
   应加入#include<afxsock.h>
哈哈,我又多得了一点经验值!;->
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值