哪位有用socket编写的客户端服务器端文件传输的代码?简单的也可以 能否给小弟一份

lm2003 2004-10-12 03:32:30
哪位有用socket编写的客户端服务器短文件传输的代码,从服务器短获取文件也算
谢谢了
...全文
201 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
lm2003 2004-10-15
  • 打赏
  • 举报
回复
哦 谢谢阿 但是我想要实现的是利用socket 从服务端下载文件并能copy的这样一个代码 你有什么建议吗?
sugelade 2004-10-14
  • 打赏
  • 举报
回复
这是一对实现在两台计算机间传送文件的函数,我没有看到过使用CSocket进行文件传送的代码,希望此代码对你有用.代码中包含两个函数,第一个用于服务器端,第二个用于客户端.
需要说明的是本文提供的方法并不适用于大型文件的传送.

下面给出服务器端代码: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();
}

最好确认服务器端函数在客户端函数之前运行,本文的代码可以方便地添加到工程中,解决服务器/客户模型中的文件传送问题.
感谢大家!
---------------------------------------------------------------
不是我写的,是VC知识库上的范例。
http://www.vckbase.com/document/viewdoc/?id=321
holywars 2004-10-14
  • 打赏
  • 举报
回复
gz
nicewinds 2004-10-14
  • 打赏
  • 举报
回复
《Network Programming for Microsoft Windows》(2nd)

在网上找找,我就在看这本书
lm2003 2004-10-13
  • 打赏
  • 举报
回复
大家帮忙一下阿 以后再补分阿
lm2003 2004-10-13
  • 打赏
  • 举报
回复
很少发帖 不知规则 还请见谅
有否源码 请予提供 不胜感谢
lifan5748 2004-10-12
  • 打赏
  • 举报
回复
晕,头一次碰到,兄弟的分给的也太多了吧
cxjddd 2004-10-12
  • 打赏
  • 举报
回复
建立 socket
传文件大小
传文件内容
传送完成 *_*

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧