服务器设计技术有很多,按使用的协议来分有 TCP 服务器和 UDP 服务器,按处理方式来分有循环服务器和并发服务器。
循环服务器与并发服务器模型
在网络程序里面,一般来说都是许多客户对应一个服务器(多对一),为了处理客户的请求,对服务端的程序就提出了特殊的要求。
目前最常用的服务器模型有:
·循环服务器:服务器在同一时刻只能响应一个客户端的请求
·并发服务器:服务器在同一时刻可以响应多个客户端的请求
UDP 循环服务器的实现方法
UDP 循环服务器每次从套接字上读取一个客户端的请求 -> 处理 -> 然后将结果返回给客户机。
因为 UDP 是非面向连接的,没有一个客户端可以老是占住服务端。只要处理过程不是死循环,或者耗时不是很长,服务器对于每一个客户机的请求在某种程度上来说是能够满足。
UDP 循环服务器模型为:
- socket(...);
- bind(...);
-
- while(1)
- {
- recvfrom(...);
- process(...);
- sendto(...);
- }
示例代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
-
- int main(int argc, char *argv[])
- {
- unsigned short port = 8080;
-
- int sockfd;
- sockfd = socket(AF_INET, SOCK_DGRAM, 0);
- if(sockfd < 0)
- {
- perror("socket");
- exit(-1);
- }
-
-
- struct sockaddr_in my_addr;
- bzero(&my_addr, sizeof(my_addr));
- my_addr.sin_family = AF_INET;
- my_addr.sin_port = htons(port);
- my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
- printf("Binding server to port %d\n", port);
-
-
- int err_log;
- err_log = bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr));
- if(err_log != 0)
- {
- perror("bind");
- close(sockfd);
- exit(-1);
- }
-
- printf("receive data...\n");
- while(1)
- {
- int recv_len;
- char recv_buf[512] = {0};
- struct sockaddr_in client_addr;
- char cli_ip[INET_ADDRSTRLEN] = "";
- socklen_t cliaddr_len = sizeof(client_addr);
-
-
- recv_len = recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr*)&client_addr, &cliaddr_len);
-
-
- inet_ntop(AF_INET, &client_addr.sin_addr, cli_ip, INET_ADDRSTRLEN);
- printf("\nip:%s ,port:%d\n",cli_ip, ntohs(client_addr.sin_port));
- printf("data(%d):%s\n",recv_len,recv_buf);
-
-
- sendto(sockfd, recv_buf, recv_len, 0, (struct sockaddr*)&client_addr, cliaddr_len);
- }
-
- close(sockfd);
-
- return 0;
- }
运行结果如下:
TCP 循环服务器的实现方法
TCP 循环服务器接受一个客户端的连接,然后处理,完成了这个客户的所有请求后,断开连接。TCP 循环服务器一次只能处理一个客户端的请求,只有在这个客户的所有请求满足后,服务器才可以继续后面的请求。如果有一个客户端占住服务器不放时,其它的客户机都不能工作了,因此,TCP 服务器一般很少用循环服务器模型的。
TCP循环服务器模型为:
- socket(...);
- bind(...);
- listen(...);
-
- while(1)
- {
- accept(...);
- process(...);
- close(...);
- }
示例代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
-
- int main(int argc, char *argv[])
- {
- unsigned short port = 8080;
-
-
- int sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd < 0)
- {
- perror("socket");
- exit(-1);
- }
-
-
- struct sockaddr_in my_addr;
- bzero(&my_addr, sizeof(my_addr));
- my_addr.sin_family = AF_INET;
- my_addr.sin_port = htons(port);
- my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
-
- int err_log = bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr));
- if( err_log != 0)
- {
- perror("binding");
- close(sockfd);
- exit(-1);
- }
-
-
- err_log = listen(sockfd, 10);
- if(err_log != 0)
- {
- perror("listen");
- close(sockfd);
- exit(-1);
- }
-
- printf("listen client @port=%d...\n",port);
-
- while(1)
- {
-
- struct sockaddr_in client_addr;
- char cli_ip[INET_ADDRSTRLEN] = "";
- socklen_t cliaddr_len = sizeof(client_addr);
-
-
- int connfd;
- connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len);
- if(connfd < 0)
- {
- perror("accept");
- continue;
- }
-
-
- inet_ntop(AF_INET, &client_addr.sin_addr, cli_ip, INET_ADDRSTRLEN);
- printf("----------------------------------------------\n");
- printf("client ip=%s,port=%d\n", cli_ip,ntohs(client_addr.sin_port));
-
-
- char recv_buf[512] = {0};
- int len = recv(connfd, recv_buf, sizeof(recv_buf), 0);
-
-
- printf("\nrecv data:\n");
- printf("%s\n",recv_buf);
-
-
- send(connfd, recv_buf, len, 0);
-
- close(connfd);
- printf("client closed!\n");
- }
-
- close(sockfd);
-
- return 0;
- }
运行结果如下:
三种并发服务器实现方法
一个好的服务器,一般都是并发服务器(同一时刻可以响应多个客户端的请求)。并发服务器设计技术一般有:多进程服务器、多线程服务器、I/O复用服务器等。
多进程并发服务器
在 Linux 环境下多进程的应用很多,其中最主要的就是网络/客户服务器。多进程服务器是当客户有请求时,服务器用一个子进程来处理客户请求。父进程继续等待其它客户的请求。这种方法的优点是当客户有请求时,服务器能及时处理客户,特别是在客户服务器交互系统中。对于一个 TCP 服务器,客户与服务器的连接可能并不马上关闭,可能会等到客户提交某些数据后再关闭,这段时间服务器端的进程会阻塞,所以这时操作系统可能调度其它客户服务进程,这比起循环服务器大大提高了服务性能。
TCP多进程并发服务器
TCP 并发服务器的思想是每一个客户机的请求并不由服务器直接处理,而是由服务器创建一个子进程来处理。
示例代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
-
- int main(int argc, char *argv[])
- {
- unsigned short port = 8080;
-
-
- int sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd < 0)
- {
- perror("socket");
- exit(-1);
- }
-
-
- struct sockaddr_in my_addr;
- bzero(&my_addr, sizeof(my_addr));
- my_addr.sin_family = AF_INET;
- my_addr.sin_port = htons(port);
- my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
-
- int err_log = bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr));
- if( err_log != 0)
- {
- perror("binding");
- close(sockfd);
- exit(-1);
- }
-
-
- err_log = listen(sockfd, 10);
- if(err_log != 0)
- {
- perror("listen");
- close(sockfd);
- exit(-1);
- }
-
- while(1)
- {
-
- char cli_ip[INET_ADDRSTRLEN] = {0};
- struct sockaddr_in client_addr;
- socklen_t cliaddr_len = sizeof(client_addr);
-
-
- int connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len);
- if(connfd < 0)
- {
- perror("accept");
- close(sockfd);
- exit(-1);
- }
-
- pid_t pid = fork();
- if(pid < 0){
- perror("fork");
- _exit(-1);
- }else if(0 == pid){
-
-
-
-
- close(sockfd);
-
- char recv_buf[1024] = {0};
- int recv_len = 0;
-
-
- memset(cli_ip, 0, sizeof(cli_ip));
- inet_ntop(AF_INET, &client_addr.sin_addr, cli_ip, INET_ADDRSTRLEN);
- printf("----------------------------------------------\n");
- printf("client ip=%s,port=%d\n", cli_ip,ntohs(client_addr.sin_port));
-
-
- while( (recv_len = recv(connfd, recv_buf, sizeof(recv_buf), 0)) > 0 )
- {
- printf("recv_buf: %s\n", recv_buf);
- send(connfd, recv_buf, recv_len, 0);
- }
-
- printf("client closed!\n");
-
- close(connfd);
-
- exit(0);
- }else if(pid > 0){
-
- close(connfd);
-
- }
- }
-
- close(sockfd);
-
- return 0;
- }
运行结果如下:
多线程服务器
多线程服务器是对多进程的服务器的改进,由于多进程服务器在创建进程时要消耗较大的系统资源,所以用线程来取代进程,这样服务处理程序可以较快的创建。据统计,创建线程与创建进程要快 10100 倍,所以又把线程称为“轻量级”进程。线程与进程不同的是:一个进程内的所有线程共享相同的全局内存、全局变量等信息,这种机制又带来了同步问题。
以下是多线程服务器模板:
示例代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
-
-
-
-
-
-
-
- void *client_process(void *arg)
- {
- int recv_len = 0;
- char recv_buf[1024] = "";
- int connfd = (int)arg;
-
-
- while((recv_len = recv(connfd, recv_buf, sizeof(recv_buf), 0)) > 0)
- {
- printf("recv_buf: %s\n", recv_buf);
- send(connfd, recv_buf, recv_len, 0);
- }
-
- printf("client closed!\n");
- close(connfd);
-
- return NULL;
- }
-
-
-
-
-
-
-
- int main(int argc, char *argv[])
- {
- int sockfd = 0;
- int connfd = 0;
- int err_log = 0;
- struct sockaddr_in my_addr;
- unsigned short port = 8080;
- pthread_t thread_id;
-
- printf("TCP Server Started at port %d!\n", port);
-
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd < 0)
- {
- perror("socket error");
- exit(-1);
- }
-
- bzero(&my_addr, sizeof(my_addr));
- my_addr.sin_family = AF_INET;
- my_addr.sin_port = htons(port);
- my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
-
- printf("Binding server to port %d\n", port);
-
-
- err_log = bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr));
- if(err_log != 0)
- {
- perror("bind");
- close(sockfd);
- exit(-1);
- }
-
-
- err_log = listen(sockfd, 10);
- if( err_log != 0)
- {
- perror("listen");
- close(sockfd);
- exit(-1);
- }
-
- printf("Waiting client...\n");
-
- while(1)
- {
- char cli_ip[INET_ADDRSTRLEN] = "";
- struct sockaddr_in client_addr;
- socklen_t cliaddr_len = sizeof(client_addr);
-
-
- connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len);
- if(connfd < 0)
- {
- perror("accept this time");
- continue;
- }
-
-
- inet_ntop(AF_INET, &client_addr.sin_addr, cli_ip, INET_ADDRSTRLEN);
- printf("----------------------------------------------\n");
- printf("client ip=%s,port=%d\n", cli_ip,ntohs(client_addr.sin_port));
-
- if(connfd > 0)
- {
-
- pthread_create(&thread_id, NULL, (void *)client_process, (void *)connfd);
- pthread_detach(thread_id);
- }
- }
-
- close(sockfd);
-
- return 0;
- }
运行结果如下:
注意,上面例子给线程传参有很大的局限性,最简单的一种情况,如果我们需要给线程传多个参数,这时候我们需要结构体传参,这种值传递编译都通不过,这里之所以能够这么值传递,是因为, int 长度时 4 个字节, void * 长度也是 4 个字节。
- int connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len);
- pthread_create(&thread_id, NULL, (void *)client_process, (void *)connfd);
如果考虑类型匹配的话,应该是这么传参,pthread_create()最后一个参数应该传地址( &connfd ),而不是值:
- int connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len);
- pthread_create(&thread_id, NULL, (void *)client_process, (void *)&connfd);
但是,如果按地址传递的话,又会有这么一个问题,假如有多个客户端要连接这个服务器,正常的情况下,一个客户端连接对应一个 connfd,相互之间独立不受影响,但是,假如多个客户端同时连接这个服务器,A 客户端的连接套接字为 connfd,服务器正在用这个 connfd 处理数据,还没有处理完,突然来了一个 B 客户端,accept()之后又生成一个 connfd, 因为是地址传递, A 客户端的连接套接字也变成 B 这个了,这样的话,服务器肯定不能再为 A 客户端服务器了,这时候,我们就需要考虑多任务的互斥或同步问题了,这里通过互斥锁来解决这个问题,确保这个connfd值被一个临时变量保存过后,才允许修改。
- #include
-
- pthread_mutex_t mutex;
-
- pthread_mutex_init(&mutex, NULL);
-
-
- pthread_mutex_lock(&mutex);
- int connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len);
-
-
- pthread_create(&thread_id, NULL, (void *)client_process, (void *)&connfd);
-
-
- void *client_process(void *arg)
- {
- int connfd = *(int *)arg;
-
-
- pthread_mutex_unlock(&mutex);
-
- return NULL;
- }
修改的完整代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
-
- pthread_mutex_t mutex;
-
-
-
-
-
-
-
- void *client_process(void *arg)
- {
- int recv_len = 0;
- char recv_buf[1024] = "";
- int connfd = *(int *)arg;
-
-
- pthread_mutex_unlock(&mutex);
-
-
- while((recv_len = recv(connfd, recv_buf, sizeof(recv_buf), 0)) > 0)
- {
- printf("recv_buf: %s\n", recv_buf);
- send(connfd, recv_buf, recv_len, 0);
- }
-
- printf("client closed!\n");
- close(connfd);
-
- return NULL;
- }
-
-
-
-
-
-
-
- int main(int argc, char *argv[])
- {
- int sockfd = 0;
- int connfd = 0;
- int err_log = 0;
- struct sockaddr_in my_addr;
- unsigned short port = 8080;
- pthread_t thread_id;
-
- pthread_mutex_init(&mutex, NULL);
-
- printf("TCP Server Started at port %d!\n", port);
-
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd < 0)
- {
- perror("socket error");
- exit(-1);
- }
-
- bzero(&my_addr, sizeof(my_addr));
- my_addr.sin_family = AF_INET;
- my_addr.sin_port = htons(port);
- my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
-
- printf("Binding server to port %d\n", port);
-
-
- err_log = bind(sockfd, (struct sockaddr*)&my_addr, sizeof(my_addr));
- if(err_log != 0)
- {
- perror("bind");
- close(sockfd);
- exit(-1);
- }
-
-
- err_log = listen(sockfd, 10);
- if( err_log != 0)
- {
- perror("listen");
- close(sockfd);
- exit(-1);
- }
-
- printf("Waiting client...\n");
-
- while(1)
- {
- char cli_ip[INET_ADDRSTRLEN] = "";
- struct sockaddr_in client_addr;
- socklen_t cliaddr_len = sizeof(client_addr);
-
-
- pthread_mutex_lock(&mutex);
-
-
- connfd = accept(sockfd, (struct sockaddr*)&client_addr, &cliaddr_len);
- if(connfd < 0)
- {
- perror("accept this time");
- continue;
- }
-
-
- inet_ntop(AF_INET, &client_addr.sin_addr, cli_ip, INET_ADDRSTRLEN);
- printf("----------------------------------------------\n");
- printf("client ip=%s,port=%d\n", cli_ip,ntohs(client_addr.sin_port));
-
- if(connfd > 0)
- {
-
- pthread_create(&thread_id, NULL, (void *)client_process, (void *)&connfd);
- pthread_detach(thread_id);
- }
- }
-
- close(sockfd);
-
- return 0;
- }
I/O复用服务器
I/O 复用技术是为了解决进程或线程阻塞到某个 I/O 系统调用而出现的技术,使进程不阻塞于某个特定的 I/O 系统调用。它也可用于并发服务器的设计,常用函数 select() 或 epoll() 来实现。详情,请看《select、poll、epoll的区别使用》。
- socket(...);
- bind(...);
- listen(...);
-
- while(1)
- {
- if(select(...) > 0)
- {
- if(FD_ISSET(...)>0)
- {
- accpet(...);
- process(...);
- }
- }
- close(...);
- }
示例代码如下:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
-
- #define SERV_PORT 8080
- #define LIST 20 //服务器最大接受连接
- #define MAX_FD 10 //FD_SET支持描述符数量
-
-
- int main(int argc, char *argv[])
- {
- int sockfd;
- int err;
- int i;
- int connfd;
- int fd_all[MAX_FD];
-
-
- fd_set fd_read;
- fd_set fd_select;
-
- struct timeval timeout;
- struct timeval timeout_select;
-
- struct sockaddr_in serv_addr;
- struct sockaddr_in cli_addr;
- socklen_t serv_len;
- socklen_t cli_len;
-
-
- timeout.tv_sec = 10;
- timeout.tv_usec = 0;
-
-
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd < 0)
- {
- perror("fail to socket");
- exit(1);
- }
-
-
- memset(&serv_addr, 0, sizeof(serv_addr));
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_port = htons(SERV_PORT);
- serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
-
-
- serv_len = sizeof(serv_addr);
-
-
- err = bind(sockfd, (struct sockaddr *)&serv_addr, serv_len);
- if(err < 0)
- {
- perror("fail to bind");
- exit(1);
- }
-
-
- err = listen(sockfd, LIST);
- if(err < 0)
- {
- perror("fail to listen");
- exit(1);
- }
-
-
- memset(&fd_all, -1, sizeof(fd_all));
-
- fd_all[0] = sockfd;
-
- FD_ZERO(&fd_read);
- FD_SET(sockfd, &fd_read);
-
- int maxfd;
- maxfd = fd_all[0];
-
- while(1){
-
-
- fd_select = fd_read;
- timeout_select = timeout;
-
-
-
- err = select(maxfd+1, &fd_select, NULL, NULL, NULL);
-
- if(err < 0)
- {
- perror("fail to select");
- exit(1);
- }
-
- if(err == 0){
- printf("timeout\n");
- }
-
-
- if( FD_ISSET(sockfd, &fd_select) ){
-
- cli_len = sizeof(cli_addr);
-
-
- connfd = accept(sockfd, (struct sockaddr *)&cli_addr, &cli_len);
- if(connfd < 0)
- {
- perror("fail to accept");
- exit(1);
- }
-
-
- char cli_ip[INET_ADDRSTRLEN] = {0};
- inet_ntop(AF_INET, &cli_addr.sin_addr, cli_ip, INET_ADDRSTRLEN);
- printf("----------------------------------------------\n");
- printf("client ip=%s,port=%d\n", cli_ip,ntohs(cli_addr.sin_port));
-
-
- for(i=0; i < MAX_FD; i++){
- if(fd_all[i] != -1){
- continue;
- }else{
- fd_all[i] = connfd;
- printf("client fd_all[%d] join\n", i);
- break;
- }
- }
-
- FD_SET(connfd, &fd_read);
-
- if(maxfd < connfd)
- {
- maxfd = connfd;
- }
-
- }
-
-
- for(i=1; i < maxfd; i++){
- if(FD_ISSET(fd_all[i], &fd_select)){
- printf("fd_all[%d] is ok\n", i);
-
- char buf[1024]={0};
- int num = read(fd_all[i], buf, 1024);
- if(num > 0){
-
-
- printf("receive buf from client fd_all[%d] is: %s\n", i, buf);
-
-
- num = write(fd_all[i], buf, num);
- if(num < 0){
- perror("fail to write ");
- exit(1);
- }else{
-
- }
-
-
- }else if(0 == num){
-
-
- printf("client:fd_all[%d] exit\n", i);
- FD_CLR(fd_all[i], &fd_read);
- close(fd_all[i]);
- fd_all[i] = -1;
-
- continue;
- }
-
- }else {
-
- }
- }
-
- }
-
- return 0;
- }
运行结果如下:
本教程示例代码下载请点此处。
参考于:http://blog.chinaunix.net