poll服务器

xiaoxiao2021-02-27  201

#include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<stdlib.h> #include<arpa/inet.h> #include<netinet/in.h> #include<poll.h> #include<unistd.h> #define SIZE 1024 static void usage(const char *proc) { printf("Usage:%s [local_ip] [local_port]\n",proc); } int startup(const char*ip,int port) { int sock = socket(AF_INET,SOCK_STREAM,0); if(sock < 0) { perror("sock"); exit(1); } struct sockaddr_in local; local.sin_family = AF_INET; local.sin_port = htons(port); local.sin_addr.s_addr = inet_addr(ip); if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0) { perror("bind"); exit(2); } if(listen(sock,10) < 0) { perror("listen"); exit(3); } return sock; } int main(int argc,char *argv[]) { if(argc != 3) { usage(argv[0]); } int listen_sock = startup(argv[1],atoi(argv[2])); struct pollfd fds[SIZE]; int i = 0; for(;i < SIZE;++i) { fds[i].fd = -1; } fds[0].fd = listen_sock; fds[0].events = POLLIN; fds[0].revents = 0; int timeout = -1; while(1) { switch(poll(fds,SIZE,timeout)) { case -1: perror("poll"); break; case 0: printf("timeout...\n"); break; default: { for(int i = 0;i < SIZE;++i) { if(fds[i].fd == listen_sock && (fds[i].revents&POLLIN)) { struct sockaddr_in client; socklen_t len = sizeof(client); int new_sock = accept(listen_sock,(struct sockaddr*)&client,&len); if(new_sock < 0) { perror("accpet"); continue; } printf("get a client:[%s] [%d]\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port)); int j = 0; for(;j < SIZE;++j) { if(fds[j].fd == -1) { break; } } if(j == SIZE) { close(new_sock); } else { fds[j].fd = new_sock; fds[j].events = POLLIN; } } else if(fds[i].fd > 0 && (fds[i].revents&POLLIN)) { char buf[1024]; printf("hello\n"); ssize_t s = read(fds[i].fd,buf,sizeof(buf)-1); if(s > 0) { buf[s] = 0; printf("client#%s\n",buf); } else if(s == 0) { printf("client is quit!!!\n"); close(fds[i].fd); fds[i].fd = -1; } else { perror("read"); close(fds[i].fd); fds[i].fd = -1; } } } } break; } } return 0; }
转载请注明原文地址: https://www.6miu.com/read-7674.html

最新回复(0)