💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
### socket文件传输 ***** ![](https://img.kancloud.cn/bd/57/bd57358564b03da4f2f205b993d98bee_1518x824.png) 遇到fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. 这不是错误,它是来自Microsoft编译器的警告。 选择项目,然后单击上下文菜单中的“属性”。 在对话框中,选择Configuration Properties- > C/C++- >Preprocessor 在PreprocessorDefinitions字段中添加;_CRT_SECURE_NO_WARNINGS以关闭这些警告。 ### server代码 ***** server.cpp ``` #include "pch.h" #include <stdio.h> #include <WinSock2.h> #pragma comment (lib, "WS2_32.lib") #define BUF_SIZE 100 int main() { const char* filename = "E:\\Development\\C++\\Custom\\Network\\TCP\\Server\\Debug\\1.txt";//文件名 const char* t = "rb"; FILE *fp = fopen(filename, t); if (fp == NULL) { printf("Connect open file , press any key exit!\n"); system("pause"); exit(0); } WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//INADDR_ANY表示任何IP sockAddr.sin_port = htons(1234); bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); listen(servSock, 20);//监听状态 SOCKADDR clntAddr;//接收客户端请求 int nSize = sizeof(SOCKADDR); SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); char buffer[BUF_SIZE]; //缓冲区 int nCount; while ((nCount = fread(buffer, 1, BUF_SIZE, fp)) > 0) { send(clntSock, buffer, nCount, 0); } shutdown(clntSock, SD_SEND);//文件读取完毕,断开输出流,向客户端发送fn包 recv(clntSock, buffer, BUF_SIZE, 0);//阻塞,等待客户端接收完毕 fclose(fp); closesocket(clntSock); //关闭套接字 closesocket(servSock); WSACleanup();//终止DLL; system("pause"); return 0; } ``` ### client 代码 ***** client.cpp ``` // Client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <stdio.h> #include <stdlib.h> #include <WinSock2.h> #include <WS2tcpip.h> #pragma comment(lib, "ws2_32.lib") #define BUF_SIZE 1024 int main() { char filename[100] = {0}; printf("Input filename to save:"); gets_s(filename, 100); FILE * fp = fopen(filename, "wb"); if (fp == NULL) { printf("Connect open file, press any key to exit\n"); system("pause"); exit(0); } WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); sockAddr.sin_port = htons(1234); if (SOCKET_ERROR == connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR))) { puts("file transfer success!"); system("pause"); return -1; } puts("Client connect successe!\n"); //connect之后可以进行输入 char buffer[BUF_SIZE] = { 0 }; int nCount; while (nCount = recv(sock, buffer, BUF_SIZE, 0) > 0) { fwrite(buffer, nCount, nCount, fp); } puts("file transfer success!"); fclose(fp); closesocket(sock); WSACleanup(); system("pause"); return 0; } ```