设为首页 加入收藏

TOP

C++利用socket的客户端和服务器之间传输文件(二)
2016-10-08 17:31:02 】 浏览:1254
Tags:利用 socket 客户端 服务器 之间 传输 文件
ource.h" using namespace std; int main() { Server server; if(!server.InitSock()) //初始化失败 { cout<<"初始化失败"< msgId) { case MSG_SEND_FILE: //客户端向服务器发送文件 cout<<"客户端请求向服务器发送文件"< fileName); cout<<"收到发送来的文件名"< fileLength; cout<<"接收到文件的长度为"< fileName); cout<<"接收的文件名为"< fileLength) { nSize=(int)(fileLength-i); } else { nSize=MAX_PACK_SIZE-1; } fread(buff,sizeof(char),nSize,pFile); int nSend; nSend=send(sd,buff,nSize,0); if(nSend==SOCKET_ERROR) { cout<<"发送失败"< #include #include #include #pragma comment(lib,"Ws2_32.lib") using namespace std; #define SERVER_IP "127.0.0.1" #define PORT 10000 class Client { public: _int64 nFileLength; char fileName[_MAX_FNAME+_MAX_EXT]; SOCKET sd; bool InitSock(); //初始化winsock u_long ResolveAdress(char *serverIp); //解析服务器地址 SOCKET ConnectServer(u_long serverIp,int port);//连接服务器 bool ProcessConnection(SOCKET sd); //客户端服务器交互 void CloseSocket(); //释放套接字 bool SendFileLength(SOCKET sd,char *filePath); //发送文件长度 bool SendFile(SOCKET sd,char *filePath); //发送文件 bool RecvCatalogInfo(SOCKET sd); //接收目录信息 bool SendDownLoadFileName(SOCKET sd); //发送要下载的文件名 bool ReceiveFileLength(SOCKET sd); //接收文件长度 bool ReceiveFileName(SOCKET sd); //接收文件名 bool ReceiveFile(SOCKET sd); //接收文件 //void DoWork(); //主体函数 }; //client.cpp #define _CRT_SECURE_NO_WARNINGS #pragma once #include #include #include #include"client.h" #include"message.h" using namespace std; int main() { Client client; if(!client.InitSock()) { cout<<"初始socket失败"< h_addr_list[0]); } } if(nAddr==INADDR_NONE) { cout<<"解析主机地址失败"< >n; switch(n) { case 1: { //向服务器发送传送文件消息 Message::MsgSendFile msgSendFile; if(send(sd,(char *)&msgSendFile,sizeof(Message::MsgSendFile),0)==SOCKET_ERROR) { cout<<"发送消息失败"< >filePath; char fileDrive[_MAX_DRIVE]; char fileDir[_MAX_DIR]; char fileName[_MAX_FNAME]; char fileExt[_MAX_EXT]; _splitpath(filePath,fileDrive,fileDir,fileName,fileExt); //将文件路径解析 Message::MsgFileName msgFileName; strcat(fileName,fileExt); strcpy(msgFileName.fileName,fileName); if(send(sd,(char *)&msgFileName,sizeof(Message::MsgFileName),0)==SOCKET_ERROR) //发送文件名 { cout<<"发送文件名出错"< nFileLength) { nSize=(int)(nFileLength-i); } else { nSize=MAX_PACK_SIZE-1; } fread(buff,sizeof(char),nSize,pFile); int nSend; nSend=send(sd,buff,nSize,0); if(nSend==SOCKET_ERROR) { cout<<"发送失败"< msgId==MSG_COMPLETE) //判断消息是否是标准消息 { cout<<"目录信息发送完成"< >fileName; Message::MsgFileName msgFileName; strcpy(msgFileName.fileName,fileName); if(send(sd,(char *)&msgFileName,MAX_PACK_SIZE,0)==SOCKET_ERROR) { cout<<"发送下载文件名出错"< fileLength; cout<<"接收到文件长度"< fileName); cout<<"接收到文件名"<
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C/C++文件IO 下一篇C++ socket TCP开发基本流程总结

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目