C++ socket完成miniFTP。本站提示廣大學習愛好者:(C++ socket完成miniFTP)文章只能為提供參考,不一定能成為您想要的結果。以下是C++ socket完成miniFTP正文
本文實例為大家分享了C++ socket完成miniFTP的辦法,供大家參考,詳細內容如下
客戶端:
服務端:
樹立銜接
銜接運用 TCP 銜接,服務器和客戶端辨別創立自己的套接字一端,服務器等候銜接,客戶端發起銜接(並指定服務器 ip)。在兩者端口號分歧且不被占用的狀況下,銜接樹立。
在整個進程中,服務器對每一個來訪的客戶端樹立一個銜接,在客戶未懇求與服務器斷開時,該銜接不斷存在,用戶可以不時向服務器收回懇求。(耐久性、流水線型銜接 )
客戶端斷開後,封閉客戶端的套接字局部,服務器持續等候新的銜接。服務器一次只能處置一個客戶端的銜接,不支持並發訪問。
PDU 格式
由於 ftp 該當支持簡直恣意類型文件,而簡直一切類型文件都能用二進制來解析,所以我們采用了二進制的格式來讀取以及寫入文件。在整個進程中,我們並不關懷文件的詳細內容,也無需在順序中解析文件,而是將其當作數據流對待。
遭到緩存區大小的限制,我們無法一次性傳輸整個文件,所以我們將文件按緩存區大小拆分紅數據包分零售送,我們可以將數據及時從緩存區寫入文件,這樣就讓出了緩存區空間。數據包僅僅包括數據,不包括頭部或尾部信息。
此外,接納文件時,recv()函數將會循環調用,因而,我們需求一個信號來告訴什麼時分發送終了。
一個想法是發送終止信號,這是可行的,但更好的辦法是在一開端發送文件總字節數,讓接納方依據剩余字節大小判別什麼時分接納終了。由於在寫入文件時,我們需求指定寫入的字節數,尤其是在發來的數據流字節數不等於緩沖區大小時。寫入字節數的錯誤解招致文件受損。
接納確認
我們知道 TCP 是牢靠傳輸協議,它采取了一系列措施來保證傳輸不會出錯。所以在運用 TCP 銜接時,我們置信數據在鏈路層上沒有出過失,它一定會成功發送到對方手上。但是在客戶端接納服務器發來的文件的時分,我們依然需求服務器發來確認信息。緣由在於,雖然我們可以保證鏈路層不出錯,但是我們無法保證使用層不出錯。例如,客戶端能夠會給出錯誤的文件名,由於接納不到服務器發來的信息,所以會墮入空等形態。
ftpClient.h
#pragma #include<winsock.h> class ftpClient { private: enum { SERVER_PORT = 9999, BUFFER_SIZE = 4096 }; sockaddr_in serverChannel; char buffer[BUFFER_SIZE]; int serverSocket; int clientSocket; bool isConnect; char name[50]; bool getFile(); bool putFile(); bool acknowledge(); bool sendRequest(char* instruction); bool connect2Host(const char* hostName); bool getWorkDir(); public: ftpClient(); ~ftpClient(); void start(); };
ftpClient.cpp
#define _CRT_SECURE_NO_WARNINGS #include"ftpClient.h" #include<cstdio> #include<io.h> #include<cstring> #include<fstream> ftpClient::ftpClient() { WORD wVersionRequested; WSADATA wsaData; int ret; //WinSock初始化: wVersionRequested = MAKEWORD(2, 2);//希望運用的WinSock DLL的版本 ret = WSAStartup(wVersionRequested, &wsaData); if (ret != 0) { printf("WSAStartup() failed!\n"); } //確認WinSock DLL支持版本2.2: if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); printf("Invalid Winsock version!\n"); } isConnect = false; } void ftpClient::start() { char c[100]; char d[100]; printf("這裡是FTP客戶端,您可以輸出help檢查操作辦法,輸出quit加入客戶端\n"); while (1) { scanf("%s", c); if (strcmp(c, "help") == 0) { printf("get [fileName] -- 下載文件\n" "put [fileName] -- 上傳文件\n" "ftp [ip] -- 登錄FTP\n" "pwd -- 顯示服務器以後任務文件夾\n" "cd [dirName] -- 更改以後文件夾\n" "close -- 封閉與以後ftp的銜接\n" "quit -- 加入客戶端\n" ); } else if (strcmp(c, "get") == 0) { scanf("%s", d); strcat(c, " "); strcat(c, d); if (!isConnect) { printf("you haven't connected to any server!\n"); } else sendRequest(c); } else if (strcmp(c, "put") == 0) { scanf("%s", d); strcat(c, " "); strcat(c, d); if (!isConnect) { printf("you haven't connected to any server!\n"); } else sendRequest(c); } else if (strcmp(c, "ftp") == 0) { scanf("%s", d); if (!isConnect&&connect2Host(d)) { isConnect = true; } else if(isConnect){ printf("you have already connected to server\n" "please close the connection before connect to a new server\n"); } } else if (strcmp(c, "pwd") == 0) { if (!isConnect) { printf("you haven't connected to any server!\n"); } else sendRequest(c); } else if (strcmp(c, "cd") == 0) { scanf("%s", d); strcat(c, " "); strcat(c, d); if (!isConnect) { printf("you haven't connected to any server!\n"); } else sendRequest(c); } else if (strcmp(c, "quit") == 0) { if (isConnect) { strcpy(c, "close"); isConnect = false; send(clientSocket, c, strlen(c) + 1, 0); closesocket(clientSocket); } break; } else if (strcmp(c, "close") == 0) { if (isConnect) { isConnect = false; send(clientSocket, c, strlen(c) + 1, 0); closesocket(clientSocket); } } else { printf("syntex error\n"); } } } bool ftpClient::connect2Host(const char* hostName) { //創立socket clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (clientSocket < 0) { printf("cannot create socket\n"); return false; } else printf("successfully create socket\n"); memset(&serverChannel, 0, sizeof(serverChannel));//初始化為0 serverChannel.sin_family = AF_INET;//channel協議家族AF_INET serverChannel.sin_addr.S_un.S_addr = inet_addr(hostName);//地址 serverChannel.sin_port = htons(SERVER_PORT);//服務器端口 //樹立銜接 serverSocket = connect(clientSocket, (sockaddr*)&serverChannel, sizeof(serverChannel)); if (serverSocket < 0) { printf("cannot connect to the host\n"); return false; } else { printf("successfully connect to the host\n"); return true; } } bool ftpClient::sendRequest(char* instruction) { int r = send(clientSocket, instruction, strlen(instruction) + 1, 0); if (r == SOCKET_ERROR) { printf("request failed\n"); return false; } else { printf("request success\n"); char opt[5]; int i = 0, j = 0; while (instruction[i] != ' '&&instruction[i] != '\0') { opt[i] = instruction[i]; i++; } opt[i] = '\0'; i++; while (instruction[i] != '\0') { name[j] = instruction[i]; i++, j++; } name[j] = '\0'; if (strcmp(opt, "get") == 0) { if (getFile()) { printf("successfully download\n"); } else printf("download failed\n"); } else if (strcmp(opt, "put") == 0) { if (putFile()) { printf("successfully upload\n"); } else printf("upload failed\n"); } else if (strcmp(opt, "pwd") == 0) { if (!getWorkDir()) printf("get work directory failed\n"); } else if (strcmp(opt, "cd") == 0) { printf("operation finished\n"); } else { printf("syntex error\n"); return false; } return true; } } bool ftpClient::getFile() { memset(buffer, 0, sizeof(buffer)); int ret; char length[20]; ret = recv(clientSocket, length, sizeof(length), 0); if (ret == SOCKET_ERROR) { return false; } else if (strcmp(length, "NAK") == 0) { return false; } int size = atoi(length); std::ofstream out; out.open(name, std::ios::binary); if (!out) { printf("cannot save the file\n"); return false; } while (size>0) { ret = recv(clientSocket, buffer, BUFFER_SIZE, 0); int s = size < BUFFER_SIZE ? size : BUFFER_SIZE; if (ret == SOCKET_ERROR) { out.close(); return false; } else if (strcmp(buffer, "NAK") == 0) { out.close(); return false; } else { out.write(buffer, s); } size -= BUFFER_SIZE; } out.close(); return acknowledge(); } bool ftpClient::putFile() { std::ifstream in; //翻開文件 in.open(name, std::ios::binary); if (!in) { printf("cannot open the file\n"); return false; } memset(buffer, 0, sizeof(buffer)); //失掉文件的字節數 in.seekg(0, std::ios_base::end); int sp = in.tellg(); int total_size = 0; int r; char length[20]; sprintf(length, "%d", sp); //發送字節 r = send(clientSocket, length, sizeof(length), 0); if (r == SOCKET_ERROR) { return false; } while (sp > 0) { in.clear(); in.seekg(total_size, std::ios_base::beg); memset(buffer, 0, sizeof(buffer)); //讀取文件 in.read(buffer, sizeof(buffer)); int size = sp < BUFFER_SIZE ? sp : BUFFER_SIZE; total_size += size; //發送文件 r = send(clientSocket, buffer, size, 0); sp -= size; if (r == SOCKET_ERROR) { in.close(); return false; } } in.close(); } bool ftpClient::getWorkDir() { printf("getWorkDir\n"); memset(buffer, 0, sizeof(buffer)); int ret; char length[20]; ret = recv(clientSocket, length, sizeof(length), 0); if (ret == SOCKET_ERROR) { return false; } int size = atoi(length); while (size>0) { ret = recv(clientSocket, buffer, BUFFER_SIZE, 0); if (ret == SOCKET_ERROR) { return false; } else { printf("%s", buffer); } size -= BUFFER_SIZE; } return true; } bool ftpClient::acknowledge() { int ret = recv(clientSocket, buffer, BUFFER_SIZE, 0); if (ret > 0) { if (strcmp(buffer, "NAK") == 0)return false; else if (strcmp(buffer, "ACK") == 0)return true; } } ftpClient::~ftpClient() { if (isConnect) { isConnect = false; char c[6]; strcpy(c, "close"); send(clientSocket, c, strlen(c) + 1, 0); closesocket(clientSocket); } }
main.cpp
#define _CRT_SECURE_NO_WARNINGS #define _WINSOCK_DEPRECATED_NO_WARNINGS #pragma(lib,"ws2_32.lib") #include"ftpClient.h" #include<stdio.h> int main() { ftpClient a; a.start(); return 0; }
ftpServer.h
#pragma once #include<winsock.h> class ftpServer { private: enum { SERVER_PORT = 9999, BUFFER_SIZE = 4096, QUEUE_SIZE = 10 }; char buffer[BUFFER_SIZE]; sockaddr_in serverChannel; char name[50]; char workDir[100]; //store like C:\Users MARK:字符串末沒有斜線!! int serverSocket; //socket int clientSocket; bool sendFile(); bool receiveFile(); bool doPwd(); bool doCd(); bool isValidPath(char* path); public: ftpServer(); bool start();//開啟服務器 }; ftpServer.cpp
#define _CRT_SECURE_NO_WARNINGS #include"ftpServer.h" #include<cstdio> #include<cstdlib> #include<fstream> #include<cstring> ftpServer::ftpServer() { WORD wVersionRequested; WSADATA wsaData; int ret; //WinSock初始化: wVersionRequested = MAKEWORD(2, 2);//希望運用的WinSock DLL的版本 ret = WSAStartup(wVersionRequested, &wsaData); if (ret != 0) { printf("WSAStartup() failed!\n"); } //確認WinSock DLL支持版本2.2: if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); printf("Invalid Winsock version!\n"); } //workDir初始化為以後途徑 system("cd > tempFile"); std::ifstream in("tempFile", std::ifstream::in); in >> workDir; in.close(); } bool ftpServer::start() { int on = 1; //初始化服務器 memset(&serverChannel, 0, sizeof(serverChannel)); serverChannel.sin_family = AF_INET; serverChannel.sin_addr.s_addr = htonl(INADDR_ANY); serverChannel.sin_port = htons(SERVER_PORT); //創立套接字 this->serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (serverSocket < 0) { printf("cannot create socket\n"); return false; } else printf("successfully create socket\n"); setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)); //綁定 int b = bind(serverSocket, (sockaddr*)&serverChannel, sizeof(serverChannel)); if (b < 0) { printf("bind error\n"); return false; } else printf("successfully bind\n"); //監聽 int l = listen(serverSocket, QUEUE_SIZE); if (l < 0) { printf("listen failed\n"); return false; } else printf("successfully listen\n"); int len = sizeof(serverChannel); //服務器等候銜接 while (1) { printf("waiting for connection...\n"); //承受一個銜接 clientSocket = accept(serverSocket, (sockaddr*)&serverChannel, &len); if (clientSocket < 0) { printf("accept failed\n"); } else { printf("successfully connect\n"); while (1) { memset(buffer, 0, sizeof(buffer)); int ret; ret = recv(clientSocket, buffer, BUFFER_SIZE, 0); if (ret == SOCKET_ERROR) { printf("receive failed\n"); } else { char opt[50]; printf("successfully receive\n"); int i = 0, j = 0; printf("buffer = %s\n", buffer); while (buffer[i] != ' '&&buffer[i] != '\0') { opt[i] = buffer[i]; i++; } opt[i] = '\0'; if (buffer[i] != '\0') { i++; } while (buffer[i] != '\0') { name[j] = buffer[i]; i++, j++; } name[j] = '\0'; if (strcmp(opt, "get") == 0) { char ret[4]; if (!sendFile()) { strcpy(ret, "NAK"); send(clientSocket, ret, sizeof(ret), 0); } else { strcpy(ret, "ACK"); send(clientSocket, ret, sizeof(ret), 0); } } else if (strcmp(opt, "put") == 0) { receiveFile(); } else if (strcmp(opt, "pwd") == 0) { doPwd(); } else if (strcmp(opt, "cd") == 0) { doCd(); } else if (strcmp(opt, "close") == 0) { break; } else { printf("syntex error\n"); } } } } } return true; } bool ftpServer::sendFile() { std::ifstream in; char path[100]; strcpy(path, workDir); strcat(path, "\\"); strcat(path, name); in.open(path, std::ios::binary); if (!in) { printf("cannot open the file\n"); return false; } memset(buffer, 0, sizeof(buffer)); in.seekg(0, std::ios_base::end); int sp = in.tellg(); int total_size = 0; int r; char length[20]; sprintf(length, "%d", sp); r = send(clientSocket, length, sizeof(length), 0); if (r == SOCKET_ERROR) { printf("send failed\n"); return false; } else { printf("send success\n"); } while (sp > 0) { in.clear(); in.seekg(total_size, std::ios_base::beg); memset(buffer, 0, sizeof(buffer)); in.read(buffer, sizeof(buffer)); int size = sp < BUFFER_SIZE ? sp : BUFFER_SIZE; total_size += size; r = send(clientSocket, buffer, size, 0); sp -= size; if (r == SOCKET_ERROR) { printf("send failed\n"); return false; } else { printf("send success\n"); } } in.close(); return true; } bool ftpServer::receiveFile() { char path[100]; strcpy(path, workDir); strcat(path, "\\"); strcat(path, name); memset(buffer, 0, sizeof(buffer)); int ret; char length[20]; ret = recv(clientSocket, length, sizeof(length), 0); if (ret == SOCKET_ERROR) { printf("receive failed\n"); return false; } else { printf("successfully receive\n"); } int size = atoi(length); std::ofstream out; out.open(path, std::ios::binary); if (!out) { printf("cannot save the file\n"); return false; } while (size>0) { int s = size < BUFFER_SIZE ? size : BUFFER_SIZE; ret = recv(clientSocket, buffer, BUFFER_SIZE, 0); if (ret == SOCKET_ERROR) { printf("receive failed\n"); break; } else { printf("successfully receive\n"); out.write(buffer, s); } size -= BUFFER_SIZE; } out.close(); return true; } bool ftpServer::doPwd() { char temCMD[150]; memset(temCMD, 0, sizeof(temCMD)); strcat(temCMD, "echo "); strcat(temCMD, workDir); strcat(temCMD, " > tempFile"); system(temCMD); memset(temCMD, 0, sizeof(temCMD)); strcat(temCMD, "dir /b "); strcat(temCMD, workDir); strcat(temCMD, " >> tempFile"); system(temCMD); std::ifstream in("tempFile", std::fstream::in); if (!in) { printf("cannot open the file\n"); return false; } memset(buffer, 0, sizeof(buffer)); in.seekg(0, std::ios_base::end); int sp = in.tellg(); int total_size = 0; int r; char length[20]; sprintf(length, "%d", sp); r = send(clientSocket, length, sizeof(length), 0); if (r == SOCKET_ERROR) { printf("send failed\n"); return false; } else { printf("send success\n"); } while (sp > 0) { in.clear(); in.seekg(total_size, std::ios_base::beg); memset(buffer, 0, sizeof(buffer)); in.read(buffer, sizeof(buffer)); int size = sp < BUFFER_SIZE ? sp : BUFFER_SIZE; total_size += size; printf("transfer size = %d\n", total_size); r = send(clientSocket, buffer, size, 0); sp -= size; if (r == SOCKET_ERROR) { printf("send failed\n"); return false; } else { printf("send success\n"); } } in.close(); return true; } bool ftpServer::isValidPath(char* path) { char temCMD[100]; memset(temCMD, 0, sizeof(temCMD)); strcat(temCMD, "cd "); strcat(temCMD, path); int res = system(temCMD); return res == 0; } bool ftpServer::doCd() { for (int i = 0; name[i] != '\0'; ++i) { if (name[i] == '/') name[i] = '\\'; } if (name[0] == '.'&&name[1] == '.') { char temDir[100]; strcpy(temDir, workDir); for (int i = sizeof(temDir); i >= 0; --i) { if (temDir[i] == '\\') { temDir[i] = '\0'; break; } } strcat(temDir, name + 2); if (isValidPath(temDir)) { strcpy(workDir, temDir); } else { return false; } } else if (name[0] == '.'&&name[1] != '.') { char temDir[100]; strcpy(temDir, workDir); strcat(temDir, name + 1); if (isValidPath(temDir)) { strcpy(workDir, temDir); } else { return false; } } else if (name[1] == ':') { if (isValidPath(name)) { strcpy(workDir, name); } else { return false; } } else { char temDir[100]; strcpy(temDir, workDir); strcat(temDir, "\\"); strcat(temDir, name); if (isValidPath(temDir)) { strcpy(workDir, temDir); } else { return false; } } return true; }
main.cpp
#include"ftpServer.h" #pragma(lib,"ws2_32.lib") int main() { ftpServer f; f.start(); }
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。