标签:
网络并发服务器设计
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <string.h>
5 #include <netinet/in.h>
6
7 #include <unistd.h>
8
9 #define portnum 3333
10
11 int main()
12 {
13 int sockfd;
14 int new_fd;
15 char buffer[128];
16 int sin_size;
17 struct sockaddr_in server_addr;
18 struct sockaddr_in client_addr;
19 int nbyte=10; //表示服务器打印前十个字节
20 int pid;
21
22 //1.创建套接字
23 if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
24 {
25 printf("creat socket error!\n");
26 exit(1);
27 }
28
29 //2.1设置绑定的地址
30 bzero(&server_addr,sizeof(struct sockaddr_in));
31 server_addr.sin_family = AF_INET;
32 server_addr.sin_port = htons(portnum);
33 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
34
35 //2.2绑定地址
36 bind(sockfd, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr));
37
38 //3.监听端口
39 listen(sockfd,5);
40
41 while(1)
42 {
43 //4.等待连接
44 sin_size = sizeof(struct sockaddr);
45 new_fd = accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size);
46 printf("server get connection %s\n",inet_ntoa(client_addr.sin_addr));
47
48 //创建子进程,由子进程处理数据通讯
49 if((pid = fork())== 0)
50 {
51 //5.接受数据
52 recv(new_fd,buffer,128,0);
53 buffer[nbyte] = ‘\0‘;
54 printf("server receive : %s\n",buffer);
55 close(new_fd);
56 close(sockfd);
57 exit(0);
58 }
59 else if(pid<0)
60 printf("fork error!\n");
61
62 //6.结束连接
63 close(new_fd);
64 }
65 close(sockfd);
66 }
与TCP服务器程序相比较添加以上特殊颜色的代码即可实现并发服务器设计:TCP服务器程序设计
标签:
原文地址:http://www.cnblogs.com/zxouxuewei/p/5380643.html