window的客户端与服务器的代码来源于
http://www.jb51.net/article/53732.htm
目前还只能实现服务器传送文件到客户端,且在客户端中要写入的文件名我已经写死了,如果要换可以自己换
windows下
server端:
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 #include <WinSock2.h> 6 7 #define PORT 8087 8 #define SERVER_IP "127.0.0.1" 9 #define BUFFER_SIZE 1024 10 #define FILE_NAME_MAX_SIZE 512 11 #pragma comment(lib, "WS2_32") 12 /*文件从服务器发往客户端,客户端中输入的文件地址应该在相应的系统内存在,在客户端中的文件名是存贮的文件名*/ 13 int main() 14 { 15 // 声明并初始化一个服务端(本地)的地址结构 16 struct sockaddr_in server_addr; 17 server_addr.sin_family = AF_INET; 18 server_addr.sin_addr.S_un.S_addr = INADDR_ANY; 19 server_addr.sin_port = htons(PORT); 20 21 22 // 初始化socket dll 23 WSADATA wsaData; 24 WORD socketVersion = MAKEWORD(2, 0); 25 if (WSAStartup(socketVersion, &wsaData) != 0) 26 { 27 printf("Init socket dll error!"); 28 exit(1); 29 } 30 31 // 创建socket 32 SOCKET m_Socket = socket(AF_INET, SOCK_STREAM, 0); 33 if (SOCKET_ERROR == m_Socket) 34 { 35 printf("Create Socket Error!"); 36 exit(1); 37 } 38 int opt = 1; 39 setsockopt(m_Socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); 40 //绑定socket和服务端(本地)地址 41 if (SOCKET_ERROR == bind(m_Socket, (LPSOCKADDR)&server_addr, sizeof(server_addr))) 42 { 43 printf("Server Bind Failed: %d", WSAGetLastError()); 44 exit(1); 45 } 46 47 //监听 48 if (SOCKET_ERROR == listen(m_Socket, 10)) 49 { 50 printf("Server Listen Failed: %d", WSAGetLastError()); 51 exit(1); 52 } 53 54 55 while (1) 56 { 57 printf("Listening To Client... "); 58 59 struct sockaddr_in client_addr; 60 int client_addr_len = sizeof(client_addr); 61 62 SOCKET m_New_Socket = accept(m_Socket, (struct sockaddr *)&client_addr, &client_addr_len); 63 if (SOCKET_ERROR == m_New_Socket) 64 { 65 printf("Server Accept Failed: %d", WSAGetLastError()); 66 break; 67 } 68 69 char buffer[BUFFER_SIZE];//="G:CodeGTK+程序设计中文版.pdf" 70 memset(buffer, 0, BUFFER_SIZE); 71 if (recv(m_New_Socket, buffer, BUFFER_SIZE, 0) < 0) 72 { 73 printf("Server Receive Data Failed!"); 74 break; 75 } 76 77 char file_name[FILE_NAME_MAX_SIZE + 1]; 78 memset(file_name, 0, FILE_NAME_MAX_SIZE + 1); 79 strncpy(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE ? FILE_NAME_MAX_SIZE : strlen(buffer)); 80 file_name[strlen(buffer)] = '