生活随笔
收集整理的這篇文章主要介紹了
Linux网络编程——tcp并发服务器(poll实现)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
https://blog.csdn.net/lianghe_work/article/details/46535859
想詳細徹底地了解poll或看懂下面的代碼請參考《Linux網(wǎng)絡(luò)編程——I/O復(fù)用之poll函數(shù)》
代碼:
#include <string.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/select.h>#include <sys/time.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <poll.h>#include <errno.h>#define OPEN_MAX 100 int main(int argc, char *argv[]){ int sockfd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in my_addr;bzero(&my_addr, sizeof(my_addr));my_addr.sin_family = AF_INET;my_addr.sin_port = htons(8000);my_addr.sin_addr.s_addr = htonl(INADDR_ANY);bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)); listen(sockfd, 10); struct pollfd client[OPEN_MAX]; int i = 0, maxi = 0; for(;i<OPEN_MAX; i++)client[i].fd = -1; client[0].fd = sockfd;client[0].events = POLLIN; while(1){ int ret = poll(client, maxi+1, -1); if((client[0].revents & POLLIN) == POLLIN ){ struct sockaddr_in cli_addr; int clilen = sizeof(cli_addr); int connfd = 0; connfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen); for(i=1; i<OPEN_MAX; i++){ if(client[i].fd < 0){client[i].fd = connfd;client[i].events = POLLIN; break;}} if(i > maxi)maxi = i; if(--ret <= 0) continue;} for(i=1; i<=maxi; i++){ if(client[i].fd < 0) continue; if(client[i].revents & (POLLIN | POLLERR)){ int len = 0; char buf[128] = ""; if((len = recv(client[i].fd, buf, sizeof(buf), 0)) < 0){ if(errno == ECONNRESET){close(client[i].fd);client[i].fd = -1;} elseperror("read error:"); } else if(len == 0){close(client[i].fd);client[i].fd = -1;} elsesend(client[i].fd, buf, len, 0); if(--ret <= 0) break; }}} return 0;}運行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的Linux网络编程——tcp并发服务器(poll实现)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。