1. #include <string.h>
    2. #include <stdio.h>
    3. #include <stdlib.h>
    4. #include <unistd.h>
    5. #include <sys/select.h>
    6. #include <sys/time.h>
    7. #include <sys/socket.h>
    8. #include <netinet/in.h>
    9. #include <arpa/inet.h>
    10. #include <sys/epoll.h>
    11. #include <errno.h>
    12. #define OPEN_MAX 100000
    13. int main()
    14. {
    15. struct epoll_event event;
    16. struct epoll_event *wait_event;
    17. int sockfd=socket(AF_INET,SOCK_STREAM,0);
    18. struct sockaddr_in server_addr;
    19. server_addr.sin_family=AF_INET;
    20. server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    21. server_addr.sin_port=htons(8001);
    22. bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
    23. listen(sockfd,100);
    24. int sockNumber[OPEN_MAX]={0};
    25. sockNumber[0]=sockfd;
    26. int crRet=epoll_create(10);
    27. if(-1==crRet)
    28. {
    29. perror("创建文件描述符失败");
    30. return 0;
    31. }
    32. event.data.fd=sockfd;
    33. event.events=EPOLLIN;
    34. int clRet=epoll_ctl(crRet,EPOLL_CTL_ADD,sockfd,&event);
    35. if(-1==clRet)
    36. {
    37. perror("注册监听事件类型失败");
    38. }
    39. int max1=0;
    40. char buf[1024]={0};
    41. while(1)
    42. { wait_event=new epoll_event[max1+1];
    43. clRet=epoll_wait(crRet,wait_event,max1+1,-1);
    44. for(int i=0;i<clRet;i++)
    45. {
    46. if((sockfd==wait_event[i].data.fd)&&(EPOLLIN==wait_event[i].events&EPOLLIN))
    47. { struct sockaddr_in cli_addr;
    48. socklen_t length = sizeof(cli_addr);
    49. sockNumber[max1+1]=accept(sockfd,(struct sockaddr*)&cli_addr,&length);
    50. if(sockNumber[max1+1]>0)
    51. {
    52. event.data.fd = sockNumber[max1+1];
    53. event.events = EPOLLIN;
    54. int ret1 = epoll_ctl(crRet, EPOLL_CTL_ADD, sockNumber[max1+1], &event);
    55. max1++;
    56. if(-1==ret1)
    57. {
    58. perror("新连接的客户端注册失败");
    59. }
    60. printf("客户端%d上线\n",max1);
    61. }
    62. }
    63. else if(wait_event[i].data.fd>3&&( EPOLLIN == wait_event[i].events & (EPOLLIN|EPOLLERR)))
    64. { memset(buf,0,sizeof(buf));
    65. int len=recv(wait_event[i].data.fd,buf,sizeof(buf),0);
    66. if(len<=0)
    67. {
    68. for(int j=1;j<=max1;j++)
    69. {
    70. if(wait_event[i].data.fd==sockNumber[j])
    71. {
    72. clRet=epoll_ctl(crRet,EPOLL_CTL_DEL,wait_event[i].data.fd,wait_event+i);
    73. printf("客户端%d下线\n",max1);
    74. sockNumber[j] =sockNumber[max1] ;
    75. close(sockNumber[max1]);
    76. sockNumber[max1] =-1;
    77. max1--;
    78. usleep(50000);
    79. }
    80. }
    81. }
    82. else
    83. {
    84. printf("%s\n",buf);
    85. }
    86. }
    87. }
    88. delete[] wait_event;
    89. }
    90. return 0;
    91. }