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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include <iostream> #include <sys/socket.h> #include <netinet/in.h> #include <cstring> #include <arpa/inet.h> #include <unistd.h> #include <sys/types.h> #include <cerrno> #include <vector> #include <fcntl.h> #include <assert.h> #include <sys/epoll.h> #include <thread> #define PORT 5000 #define SERVER_IP "127.0.0.1" #define MAX_EVENTS 5
void set_nonblocking(int sockfd){ int flags = fcntl(sockfd, F_GETFL); flags |= O_NONBLOCK; fcntl(sockfd, F_SETFL, flags); }
int main(){ int listen_fd = socket(AF_INET, SOCK_STREAM, 0); assert(listen_fd >= 1); struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(PORT); inet_pton(AF_INET, SERVER_IP, &address.sin_addr); int ret = bind(listen_fd, (struct sockaddr*)(&address), sizeof(address)); assert(ret != -1); int ret1 = listen(listen_fd, 5); assert(ret1 != -1); set_nonblocking(listen_fd);
int epoll_fd = epoll_create1(0); assert(epoll_fd != -1);
struct epoll_event ev; ev.events = EPOLLIN | EPOLLET; ev.data.fd = listen_fd;
if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &ev) == -1){ std::cerr << "Failed to add file descriptor to epoll" << std::endl; close(epoll_fd); return 1; }
struct epoll_event events[MAX_EVENTS];
while(true){ int nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1); for(int i = 0; i < nfds; ++i){ if(events[i].data.fd == listen_fd){ struct sockaddr_in client; socklen_t client_len = sizeof(client); int sock_fd = accept(listen_fd, (struct sockaddr*)(&client), &client_len); set_nonblocking(sock_fd); ev.events = EPOLLIN | EPOLLET; ev.data.fd = sock_fd; if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock_fd, &ev) == -1){ std::cerr << "Failed to add client socket file descriptor to epoll" << std::endl; } } else{ int client_fd = events[i].data.fd; char buf[1024] = {0}; int recv_size;
while((recv_size = recv(client_fd, buf, sizeof(buf), 0)) > 0){ std::cout << "服务端接收到的消息为:" << buf << std::endl; send(client_fd, buf, sizeof(buf), 0); }
if(recv_size == 0 || (recv_size == -1 && errno != EAGAIN && errno != EWOULDBLOCK)){ if(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client_fd, &ev) == -1){ std::cerr << "Failed delete the client_fd" << std::endl; } close(client_fd); } } } } close(listen_fd); close(epoll_fd); return 0; }
|