原文:http://blog.csdn.net/yfkiss/article/details/7553832
本文通过一个简单的例子,介绍网络服务器编程模型
服务器接受客户端连接请求,回显客户端发过来的数据,发送当前时间给客户端
所有源码可打包下载:
http://download.csdn.net/detail/yfkiss/4318990
客户端请求相关代码:
- //和服务器建立连接
- if(connect(sockfd,(struct sockaddr *)&their_addr,sizeof(struct sockaddr))==-1)
- {
- perror("connect");
- exit(1);
- }
- //向服务器发送请求
- if(send(sockfd,buf,strlen(buf),0)==-1)
- {
- perror("send");
- exit(1);
- }
- memset(buf,0,sizeof(buf));
- //接受从服务器返回的信息
- if((numbytes = recv(sockfd,buf,100,0))==-1)
- {
- perror("recv");
- exit(1);
- }
- else
- {
- printf("Time: %s\n", buf);
- }
简单服务器模型
服务器进程接受连接,处理请求,然后等待下一个连接,如图:- //等待连接
- while(1)
- {
- struct sockaddr cliaddr;
- sin_size = sizeof(struct sockaddr);
- //接受连接
- if((new_fd = accept(sockfd, (struct sockaddr *)&cliaddr, (socklen_t*)&sin_size))==-1)
- {
- perror("accept");
- return -1;
- }
- char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
- getnameinfo(&cliaddr, sizeof(cliaddr), hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICHOST | NI_NUMERICSERV);
- printf("Accepted connection: host=%s, port=%s\n", hbuf, sbuf);
- //读取客户端发来的信息
- memset(buff,0,sizeof(buff));
- if((numbytes = recv(new_fd,buff,sizeof(buff),0))==-1)
- {
- perror("recv");
- return -1;
- }
- //获取系统时间
- time_t now = time(0);
- sprintf(buff, "Server Time is : %s", ctime(&now));
- //将从客户端接收到的信息再发回客户端
- if(send(new_fd,buff,strlen(buff),0)==-1)
- {
- perror("send");
- }
- //关闭连接
- close(new_fd);
- }
多进程模型
服务器进程接受连接,fork一个子进程为客户服务,然后等待下一个连接。多进程模型适用于单个客户服务需要消耗较多的 CPU 资源,例如需要进行大规模或长时间的数据运算或文件访问。多进程模型具有较好的安全性。
如图:
- //等待连接
- while(1)
- {
- struct sockaddr cliaddr;
- sin_size = sizeof(struct sockaddr);
- //接受连接
- if((new_fd = accept(sockfd, (struct sockaddr *)&cliaddr, (socklen_t*)&sin_size))==-1)
- {
- perror("accept");
- return -1;
- }
- char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
- getnameinfo(&cliaddr, sizeof(cliaddr), hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICHOST | NI_NUMERICSERV);
- printf("Accepted connection: host=%s, port=%s\n", hbuf, sbuf);
- //fork子进程处理请求
- if(!fork())
- {
- process(new_fd);
- //关闭连接
- close(new_fd);
- return 0;
- }
- }
- close(sockfd);
- }
多线程模型
和多进程模型类似,服务器进程接受连接,新建一个线程为客户服务,然后等待下一个连接和多进程相比,由于进程消耗的资源比线程大的多,因此,在需要为较多客户端服务的时候,优先使用多线程。
如图:
- void* process(void* arg)
- {
- int new_fd = *(int*)arg;
- char buff[1024];
- int numbytes;
- //读取客户端发来的信息
- memset(buff,0,sizeof(buff));
- if((numbytes = recv(new_fd,buff,sizeof(buff),0))==-1)
- {
- perror("recv");
- return NULL;
- }
- //获取系统时间
- time_t now = time(0);
- sprintf(buff, "Server Time is : %s", ctime(&now));
- //将从客户端接收到的信息再发回客户端
- if(send(new_fd,buff,strlen(buff),0)==-1)
- {
- perror("send");
- return NULL;
- }
- close(new_fd);
- pthread_exit(NULL);
- return NULL;
- }
- int main()
- {
- ......
- //等待连接
- while(1)
- {
- struct sockaddr cliaddr;
- sin_size = sizeof(struct sockaddr);
- //接受连接
- if((new_fd = accept(sockfd, (struct sockaddr *)&cliaddr, (socklen_t*)&sin_size))==-1)
- {
- perror("accept");
- return -1;
- }
- char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
- getnameinfo(&cliaddr, sizeof(cliaddr), hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICHOST | NI_NUMERICSERV);
- printf("Accepted connection: host=%s, port=%s\n", hbuf, sbuf);
- //创建新线程为客户端服务
- if((pthread_create(&thread, NULL, process, (void*)(&new_fd))))
- {
- perror("pthread_create error");
- return 0;
- }
- }
- close(sockfd);
- }
事件驱动模型
多线程模型通过将连接与线程绑定的方式,较好的解决了同一时刻为多个客户提供请求的要求,但是,如果客户请求数成千上万,即使是线程,服务器也无法承受庞大的资源消耗。当然,我们可以通过使用线程池来控制线程数量,减少资源开销,但是,面对大的服务压力,池本身无法增加承载能力。
事件驱动模型使用IO复用(参考网络编程--IO模型示例),在每一个执行周期都会探测一次或一组事件,一个特定的事件会触发某个特定的响应。
相比其他模型,事件驱动模型优点是只用单线程执行,占用资源少,不消耗太多 CPU,同时能够为多客户端提供服务。缺点是程序逻辑复杂,编程复杂性较高。
如图:
核心代码:
- #define MAX_EVENTS 1024
- struct myevent_s
- {
- int fd;
- void (*call_back)(int fd, int events, void *arg);
- int events;
- void *arg;
- int status; // 1: in epoll wait list, 0 not in
- char buff[128]; // recv data buffer
- int len;
- long last_active; // last active time
- };
- int g_epollFd;
- myevent_s g_Events[MAX_EVENTS+1]; // g_Events[MAX_EVENTS] is used by listen fd
- void RecvData(int fd, int events, void *arg);
- void SendData(int fd, int events, void *arg);
- // set event
- void EventSet(myevent_s *ev, int fd, void (*call_back)(int, int, void*), void *arg)
- {
- ev->fd = fd;
- ev->call_back = call_back;
- ev->events = 0;
- ev->arg = arg;
- ev->status = 0;
- ev->len = 0;
- ev->last_active = time(NULL);
- }
- // add/mod an event to epoll
- void EventAdd(int epollFd, int events, myevent_s *ev)
- {
- struct epoll_event epv = {0, {0}};
- int op;
- epv.data.ptr = ev;
- epv.events = ev->events = events;
- if(ev->status == 1){
- op = EPOLL_CTL_MOD;
- }
- else{
- op = EPOLL_CTL_ADD;
- ev->status = 1;
- }
- if(epoll_ctl(epollFd, op, ev->fd, &epv) < 0)
- printf("Event Add failed[fd=%d]\n", ev->fd);
- else
- printf("Event Add OK[fd=%d]\n", ev->fd);
- }
- // delete an event from epoll
- void EventDel(int epollFd, myevent_s *ev)
- {
- struct epoll_event epv = {0, {0}};
- if(ev->status != 1) return;
- epv.data.ptr = ev;
- ev->status = 0;
- epoll_ctl(epollFd, EPOLL_CTL_DEL, ev->fd, &epv);
- }
- // accept new connections from clients
- void AcceptConn(int fd, int events, void *arg)
- {
- struct sockaddr_in sin;
- socklen_t len = sizeof(struct sockaddr_in);
- int nfd, i;
- // accept
- if((nfd = accept(fd, (struct sockaddr*)&sin, &len)) == -1)
- {
- if(errno != EAGAIN && errno != EINTR)
- {
- printf("%s: bad accept", __func__);
- }
- return;
- }
- do
- {
- for(i = 0; i < MAX_EVENTS; i++)
- {
- if(g_Events[i].status == 0)
- {
- break;
- }
- }
- if(i == MAX_EVENTS)
- {
- printf("%s:max connection limit[%d].", __func__, MAX_EVENTS);
- break;
- }
- // set nonblocking
- if(fcntl(nfd, F_SETFL, O_NONBLOCK) < 0) break;
- // add a read event for receive data
- EventSet(&g_Events[i], nfd, RecvData, &g_Events[i]);
- EventAdd(g_epollFd, EPOLLIN|EPOLLET, &g_Events[i]);
- printf("new conn[%s:%d][time:%d]\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), g_Events[i].last_active);
- }while(0);
- }
- // receive data
- void RecvData(int fd, int events, void *arg)
- {
- struct myevent_s *ev = (struct myevent_s*)arg;
- int len;
- // receive data
- len = recv(fd, ev->buff, sizeof(ev->buff)-1, 0);
- EventDel(g_epollFd, ev);
- if(len > 0)
- {
- ev->len = len;
- ev->buff[len] = '\0';
- printf("C[%d]:%s\n", fd, ev->buff);
- // change to send event
- EventSet(ev, fd, SendData, ev);
- EventAdd(g_epollFd, EPOLLOUT|EPOLLET, ev);
- }
- else if(len == 0)
- {
- close(ev->fd);
- printf("[fd=%d] closed gracefully.\n", fd);
- }
- else
- {
- close(ev->fd);
- printf("recv[fd=%d] error[%d]:%s\n", fd, errno, strerror(errno));
- }
- }
- // send data
- void SendData(int fd, int events, void *arg)
- {
- struct myevent_s *ev = (struct myevent_s*)arg;
- int len;
- time_t now = time(0);
- sprintf(ev->buff, "Server Time is : %s", ctime(&now));
- // send data
- len = send(fd, ev->buff, strlen(ev->buff), 0);
- ev->len = 0;
- EventDel(g_epollFd, ev);
- if(len > 0)
- {
- // change to receive event
- EventSet(ev, fd, RecvData, ev);
- EventAdd(g_epollFd, EPOLLIN|EPOLLET, ev);
- }
- else
- {
- close(ev->fd);
- printf("recv[fd=%d] error[%d]\n", fd, errno);
- }
- }
- void InitListenSocket(int epollFd, short port)
- {
- int listenFd = socket(AF_INET, SOCK_STREAM, 0);
- fcntl(listenFd, F_SETFL, O_NONBLOCK); // set non-blocking
- printf("server listen fd=%d\n", listenFd);
- EventSet(&g_Events[MAX_EVENTS], listenFd, AcceptConn, &g_Events[MAX_EVENTS]);
- // add listen socket
- EventAdd(epollFd, EPOLLIN|EPOLLET, &g_Events[MAX_EVENTS]);
- // bind & listen
- sockaddr_in sin;
- bzero(&sin, sizeof(sin));
- sin.sin_family = AF_INET;
- sin.sin_addr.s_addr = INADDR_ANY;
- sin.sin_port = htons(port);
- bind(listenFd, (const sockaddr*)&sin, sizeof(sin));
- listen(listenFd, 5);
- }
- int main(int argc, char **argv)
- {
- short port = 7092; // default port
- // create epoll
- g_epollFd = epoll_create(MAX_EVENTS);
- if(g_epollFd <= 0) printf("create epoll failed.%d\n", g_epollFd);
- // create & bind listen socket, and add to epoll, set non-blocking
- InitListenSocket(g_epollFd, port);
- // event loop
- struct epoll_event events[MAX_EVENTS];
- printf("server running:port[%d]\n", port);
- int checkPos = 0;
- while(1){
- // a simple timeout check here, every time 100, better to use a mini-heap, and add timer event
- long now = time(NULL);
- for(int i = 0; i < 100; i++, checkPos++) // doesn't check listen fd
- {
- if(checkPos == MAX_EVENTS) checkPos = 0; // recycle
- if(g_Events[checkPos].status != 1) continue;
- long duration = now - g_Events[checkPos].last_active;
- if(duration >= 60) // 60s timeout
- {
- close(g_Events[checkPos].fd);
- printf("[fd=%d] timeout[%d--%d].\n", g_Events[checkPos].fd, g_Events[checkPos].last_active, now);
- EventDel(g_epollFd, &g_Events[checkPos]);
- }
- }
- // wait for events to happen
- int fds = epoll_wait(g_epollFd, events, MAX_EVENTS, 1000);
- if(fds < 0){
- printf("epoll_wait error, exit\n");
- break;
- }
- for(int i = 0; i < fds; i++){
- myevent_s *ev = (struct myevent_s*)events[i].data.ptr;
- if((events[i].events&EPOLLIN)&&(ev->events&EPOLLIN)) // read event
- {
- ev->call_back(ev->fd, events[i].events, ev->arg);
- }
- if((events[i].events&EPOLLOUT)&&(ev->events&EPOLLOUT)) // write event
- {
- ev->call_back(ev->fd, events[i].events, ev->arg);
- }
- }
- }
- // free resource
- return 0;
- }
总结:
多进程和多线程适用于小规模,长连接的场景
事件驱动适用于大规模、IO密集、大量慢连接、短连接的场景