Linux poll服务器
来源:互联网 发布:微信数据怎么放到sd卡 编辑:程序博客网 时间:2024/06/05 17:15
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <sys/types.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>#include <poll.h>#define MAX_POLL_SIZE 128static void usage(char* arg){ printf("Usage:%s[local_ip][local_port]\n",arg);}int starup(const char* ip,int port){ int sock = socket(AF_INET,SOCK_STREAM,0); if(sock < 0) { perror("socket"); exit(2); } struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = inet_addr(ip); int opt = 1; setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); if(bind(sock,(struct sockaddr*)&server,sizeof(server)) < 0) { perror("bind"); exit(3); } if(listen(sock,5) < 0) { perror("listen"); exit(4); } return sock;}int main(int argc,char* argv[]){ if(3 != argc) { usage(argv[0]); return 1; } int listen_sock = starup(argv[1],atoi(argv[2])); struct pollfd fds[MAX_POLL_SIZE]; fds[0].fd = listen_sock; fds[0].events = POLLIN; int i = 1; for(;i<MAX_POLL_SIZE;++i) { fds[i].fd=-1; } while(1) { int num = poll(fds,MAX_POLL_SIZE,-1); switch(num) { case 0: printf("nothing ready\n"); break; case -1: perror("poll"); break; default: { for(i = 0;i < MAX_POLL_SIZE; ++ i) { if(fds[i].fd == -1) continue; else if(i == 0 && fds[0].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("accept"); continue; } printf("get a new client:%s %d\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port)); int j = 1; for(;j < MAX_POLL_SIZE; ++j) { if(fds[j].fd == -1) break; } if(j < MAX_POLL_SIZE) { fds[j].fd = new_sock; fds[j].events = POLLIN | POLLOUT; } else { printf("servet is busy!!\n"); close(new_sock); } } else if(fds[i].revents & POLLIN) { char buf[1024]; ssize_t s = read(fds[i].fd,buf,sizeof(buf)-1); if(s < 0) { perror("read "); close(fds[i].fd); fds[i].fd=-1; continue; } else if(s == 0) { printf("client quit!!\n"); close(fds[i].fd); fds[i].fd=-1; continue; } buf[s]=0; printf("%s\n",buf); } else if(fds[i].revents & POLLOUT) { char* buf = "hello word"; write(fds[i].fd,buf,strlen(buf)); close(fds[i].fd); fds[i].fd=-1; printf("server close client\n"); } }//for }//default }//switch }//while return 0;}
阅读全文
0 0
- Linux poll服务器
- Linux网络编程/poll服务器
- select和poll服务器实现(Linux)
- Linux epoll服务器、epoll、poll、select优缺点
- poll服务器
- poll服务器
- poll服务器
- poll服务器
- poll服务器
- poll服务器
- poll服务器
- poll服务器
- poll服务器
- linux poll
- Linux - poll()
- Linux poll
- Linux poll
- Linux中poll实现高性能服务器及优缺点总结
- pm2 监控nodejs项目 常用命令小记
- CXF实现简单webservice应用、集成spring发布到tomcat
- 通过NTP服务器获取网络时间C++
- Eclipse-Android-Maven from Integrated plugin to Created
- 电压的降额 Voltage Derating
- Linux poll服务器
- 人见人爱A^B
- [J2EE规范]RMI简单实例
- 邮件营销之第一印象,从欢迎信开始就“套牢”用户!
- java.util.concurrent 框架概览
- opencv 2 图像平滑处理
- go get 命令 i/o timeout 解决办法
- Unity5的AssetBundle(一、打包)
- Tomcat 的 JDBC 连接池