VC中小弟我用socket创建套接字传输文件。但是只能传输txt文件。请教怎样让其传输任意格式的文件
VC中我用socket创建套接字传输文件。但是只能传输txt文件。请问怎样让其传输任意格式的文件。
请大神帮忙指导一下,怎么改才行。要详细点我很菜
------解决方案--------------------
对于CFile打开用 CFile::typeBinary 就是二进制格式,也可以直接用C库函数 fopen("file_name", "rb+"); 发送文件的操作你可以参考《WinSock网络编程经络》第16章WebSrv和WebClnt,这里是源码地址:
http://download.csdn.net/detail/geoff08zhang/4571358。
------解决方案--------------------
- C/C++ code
// fasong.cpp : Defines the entry point for the console application.// The one and only application object CWinApp theApp; using namespace std; void SendFile(LPCTSTR strFilename) { AfxSocketInit(NULL); //BOOL AfxSocketInit( WSADATA* lpwsaData = NULL ); 加载套接字库 CSocket sockSrvr; sockSrvr.Create(800); sockSrvr.Listen(); CSocket sockRecv; sockSrvr.Accept(sockRecv); CFile myFile; if(!myFile.Open(strFilename, CFile::modeRead | CFile::typeBinary)) return; int myFileLength = myFile.GetLength(); sockRecv.Send(&myFileLength, 4); byte* data = new byte[myFileLength]; myFile.Read(data, myFileLength); //1024 int iRet ; iRet = sockRecv.Send(data, myFileLength); cout << "包含字节数 = " << iRet << endl; cout << " 发送文件结束 " << endl; myFile.Close(); delete data; sockSrvr.Close();} int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { // TODO: code your application's behavior here. //SendFile("C:\\autoexec.bat"); cout << "开始发送文件" << endl; SendFile("G:\\123.docx"); getchar(); } return nRetCode; } // kefu.cpp : Defines the entry point for the console application.// CWinApp theApp;using namespace std;//#define PORT 34000void GetFile(LPCTSTR strFilename) {AfxSocketInit(NULL);CSocket sockkefu; sockkefu.Create(); sockkefu.Connect("127.0.0.1",800); int dataLength; sockkefu.Receive(&dataLength, 4);byte* data = new byte[dataLength];sockkefu.Receive(data, dataLength); //然后开始下载文件 CFile destFile(strFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);destFile.Write(data, dataLength); //写入数据destFile.Close();cout << "接受数据完成" << endl;delete data; sockkefu.Close();} int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]){int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)){// TODO: change error code to suit your needscerr << _T("Fatal Error: MFC initialization failed") << endl;nRetCode = 1;}else{// TODO: code your application's behavior here.cout << " 开始接受数据 " << endl;GetFile("G:\\123copy.docx");return nRetCode;} return nRetCode;}
请大神帮忙指导一下,怎么改才行。要详细点我很菜
------解决方案--------------------
对于CFile打开用 CFile::typeBinary 就是二进制格式,也可以直接用C库函数 fopen("file_name", "rb+"); 发送文件的操作你可以参考《WinSock网络编程经络》第16章WebSrv和WebClnt,这里是源码地址:
http://download.csdn.net/detail/geoff08zhang/4571358。
------解决方案--------------------