标签:
并发服务器设计
采用多进程来处理
tcp_server_fork.c
1 #include <stdio.h> 2 #include <sys/socket.h> 3 #include <string.h> 4 #include <netinet/in.h> 5 6 #define portnum 3333 7 8 int main() 9 { 10 int sockfd ,new_fd; 11 struct sockaddr_in server_addr; 12 struct sockaddr_in client_addr; 13 char buffer[128]; 14 int nbyte; 15 int sin_size; 16 int pid; 17 //创建套接字 18 if((sockfd = socket(AF_INET,SOCK_STREAM,0))== -1) 19 { 20 printf("create socket error.\n"); 21 exit(1); 22 } 23 //2.1设置要绑定的地址 24 bzero(&server_addr,sizeof(struct sockaddr_in)); 25 sockaddr_in.sin_family = AF_INET; 26 sockaddr_in.sin_port = htons(portnum);//客户机转为网络字符序 27 sockaddr_in.sin_addr.s_addr = htonl(INADDR_ANY);//客户机转为网络字符序 28 //2.2绑定地址 29 bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr)); 30 //3.监听端口 31 listen(sockfd,5); 32 while(1) 33 { 34 //4.等待连接 35 sin_size = sizeof(struct sockaddr); 36 new_fd = accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size); 37 printf("server get connection from %s\n",inet_ntoa(client_addr.sin_addr)); 38 39 //由子进程来处理数据通讯 40 if(pid = fork() == 0) 41 { 42 //5.接收数据 43 nbyte = recv(new_fd,buffer,128,0); 44 buffer[nbyte]=‘\0‘; 45 printf("server received : %s\n",buffer); 46 47 close(new_fd); 48 close(sockfd); 49 exit(0); 50 } 51 else if(pid <0) 52 { 53 printf("fork error!\n"); 54 } 55 //6.结束连接 56 colse(new_fd); 57 58 } 59 close(sockfd); 60 61 return 0; 62 }
tcp_client.c
1 #include <stdio.h> 2 #include <string.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 5 6 #define portnum 3333 7 8 int main() 9 { 10 struct sockaddr_in server_addr; 11 int sockfd; 12 char buffer[128]; 13 14 //1.创建套接字 15 if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) 16 { 17 printf("create socket error.\n"); 18 exit(1); 19 } 20 //2.1设置要链接的服务器的地址 21 bzero(&server_addr,sizeof(struct sockaddr_in)); 22 server_addr.sin_family = AF_INET; 23 server_addr.sin_port = htons(portnum); 24 server_addr.sin_addr.s_addr = inet_addr("192.168.1.113");//服务器IP地址 25 //2.链接服务器 26 if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr)) == -1) 27 { 28 printf("connect error.\n"); 29 exit(1); 30 } 31 //3.发送数据到服务器 32 printf("Please input char:\n"); 33 fgets(buffer,128,stdin); 34 send(sockfd,buffer,strlen(buffer),0); 35 //4.关闭连接 36 close(sockfd); 37 38 return 0; 39 }
标签:
原文地址:http://www.cnblogs.com/love-linux/p/5223822.html