服务器端程序:
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/shm.h> #define BUF_SIZE 1024 #define SERVER_PORT 1234 int main() { char *filename = "sendfile.txt"; FILE *fp = fopen(filename,"rb" ); if(fp == NULL ) { printf("open file error!!\r\n"); exit(1); } else { printf("open file succeed\r\n"); } int server_sockfd = socket(AF_INET,SOCK_STREAM,0); ///bind listen struct sockaddr_in server_sockAddr; memset(&server_sockAddr,0 , sizeof(server_sockAddr)); server_sockAddr.sin_family = PF_INET; server_sockAddr.sin_addr.s_addr = htonl(INADDR_ANY); server_sockAddr.sin_port = htons(SERVER_PORT); if(bind(server_sockfd,(struct sockaddr *)&server_sockAddr,\ sizeof(server_sockAddr) ) == -1) { perror("bind error\r\n"); exit(1); } if(listen(server_sockfd,20) == -1) { perror("listen error\r\n"); exit(1); } ///accept struct sockaddr_in client_addr; int clnSize = sizeof(client_addr); int conn = accept(server_sockfd,(struct sockaddr*)&client_addr,&clnSize); if(conn <0) { perror("accept error!\r\n"); exit(1); } /// 循环发送文件直到末尾; char buffer[BUF_SIZE]={0}; int send_len = 0; while((send_len = fread(buffer,1, BUF_SIZE,fp)) >0) { send(conn, buffer, send_len, 0); } shutdown( conn, SHUT_WR); recv(conn,buffer,BUF_SIZE, 0); fclose(fp); close(conn); close(server_sockfd); return 0; }
客户端程序:
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/shm.h> int main() { ///手动输入创建你文件 char filename[100]; //保存文件名 printf("input the file name: "); gets(filename); //scanf("Input file name to save:%s ", filename); FILE *fp = fopen(filename, "wb"); if(fp == NULL){ printf("open file failed!!\r\n"); exit(1); } //定义客户端socketfd int sock_cli = socket(PF_INET,SOCK_STREAM, IPPROTO_TCP); //connect struct sockaddr_in serveraddr; serveraddr.sin_family = PF_INET; serveraddr.sin_port = htons(1234); serveraddr.sin_addr.s_addr =inet_addr("127.0.0.1"); if (connect(sock_cli,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) <0) { perror("connect failed!\r\n"); exit(1); } int ncount = 0; char recvbuf[1024] = {0}; while( (ncount = recv(sock_cli, recvbuf, 1024, 0)) >0) { fwrite(recvbuf, 1, ncount, fp); } puts("file transfer succeed!!\r\n"); memset(recvbuf, 0, 1024); fclose(fp); close(sock_cli); return 0; }
然后呢我们在linux命令行下对这两个文件分别编译,别说你不会编译的命令哈。
先执行服务器端的程序
再执行客户端的程序:
完了后你会发现当前目录下多了一个你在客户端手动创建的文件,文件内容与服务器端传送过来的文件内容一致!
总结下:其实呢,socket的文件传输和socket一般的字符串通信差不多的,将文件的内容读出来发送到对端而已。