1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <sys/epoll.h> #include <sys/socket.h> #include <unistd.h> #include <thread>
int main() { auto sfd = socket(AF_INET, SOCK_STREAM, 0); if (sfd == -1) { printf("socket error\n"); return 1; } sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(10000); int err = bind(sfd, (sockaddr*)&addr, sizeof(sockaddr)); if (err < 0) { printf("bind error\n"); return 1; } err = listen(sfd, 50); if (err == -1) { printf("listen error %d %s\n", errno, strerror(errno)); return 1; } auto efd = epoll_create(1); std::thread task_print([efd]() { epoll_event events[20]; char buffer[1000]; for (;;) { auto fds = epoll_wait(efd, events, 20, -1); if (fds == -1) { printf("epoll_wait error %d %s\n", errno, strerror(errno)); continue; } for (auto i = 0; i < fds; i++) { if (events[i].events & EPOLLRDHUP) { epoll_ctl(efd, EPOLL_CTL_DEL, events[i].data.fd, &events[i]); } if (events[i].events & EPOLLIN) { auto len = recv(events[i].data.fd, buffer, 3, 0); buffer[len] = 0; printf("read %s\n", buffer); } } } }); for (;;) { int connfd; sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); if ((connfd = accept(sfd, (sockaddr*)&client_addr, &client_addr_len)) == -1) { printf("error\n"); continue; } epoll_event evt; evt.events = EPOLLIN | EPOLLRDHUP; evt.data.fd = connfd; err = epoll_ctl(efd, EPOLL_CTL_ADD, connfd, &evt); if (err == -1) { printf("epoll_ctl add error %d %s\n", errno, strerror(errno)); } } return 0; }
|