服务端:
#include <stdio.h> #include <winsock2.h> #pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll #define BUF_SIZE 1024 int main(int argc, char *argv[]){ //先检查文件是否存在 char *filename = "Beyond.mp3";//文件名 FILE *fp = fopen(filename, "rb");//以二进制方式打开文件 if(fp == NULL) { printf("Cannot open file, press any key to exit!\n"); system("pause"); exit(0); } //初始化 DLL WSADATA wsaData; WSAStartup( MAKEWORD(2, 2), &wsaData); //创建套接字 SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(servSock == INVALID_SOCKET) { printf("Failed socket().\n"); WSACleanup(); return 0; } //绑定套接字 struct sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充 sockAddr.sin_family = PF_INET; //使用IPv4地址 sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址 sockAddr.sin_port = htons(1234); //端口 if(bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)) == SOCKET_ERROR) { printf("Failed bind().\n"); WSACleanup(); return 0; } //进入监听状态 listen(servSock, 20); //循环接收客户端请求 int nSize = sizeof(SOCKADDR); char buffer[BUF_SIZE] = {0};//缓冲区 SOCKADDR clntAddr; SOCKET clntSock; for(;;) { clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize); if(clntSock == INVALID_SOCKET) { printf("Failed accept().\n"); continue; } int nCount; while(nCount = fread(buffer, 1, BUF_SIZE, fp) > 0) { send(clntSock, buffer, nCount, 0);//循环发送数据,直到文件结尾 } shutdown(clntSock, SD_SEND);//文件读取完毕,断开输出流,向客户端发送FIN包 recv(clntSock, buffer, BUF_SIZE, 0);//阻塞,等待客户端接收完毕 memset(buffer, 0, BUF_SIZE);//设置缓冲区 fclose(fp); closesocket(clntSock); } //关闭套接字 closesocket(servSock); //终止 DLL 的使用 WSACleanup(); system("pause"); return 0; }
客户端:
#include <stdio.h> #include <stdlib.h> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") #define BUF_SIZE 1024 int main(int argc, char *agrv[]) { //先输入文件名,看文件是否能创建成功 char filename[100] = {0}; //文件名 printf("Input filename to save: "); gets(filename); FILE *fp = fopen(filename, "wb");//以二进制方式打开(创建)文件 if(fp == NULL) { printf("Cannot open file, press any key to exit!\n"); system("pause"); exit(0); } //初始化DLL WSADATA wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); //创建套接字 SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock == INVALID_SOCKET) { printf("Failed socket().\n"); WSACleanup(); return 0; } //向服务器发起请求 struct sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充 sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); sockAddr.sin_port = htons(1234); if(connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)) == -1) { printf("Failed connect().\n"); WSACleanup(); return 0; } //循环接受数据,知道文件传输完毕 char buffer[BUF_SIZE] = {0}; //文件缓冲区 int nCount; while((nCount = recv(sock, buffer, BUF_SIZE, 0)) > 0) { fwrite(buffer, nCount, 1, fp); } puts("File transfer success!\n"); memset(buffer, 0, BUF_SIZE);//重置缓冲区 fclose(fp); closesocket(sock); //终止使用DLL WSACleanup(); system("pause"); return 0; }