#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#define MAX_EVENTS 1024
#define BUF_SIZE 4096
using namespace std;
int main(int argc, char* argv[])
{
int listen_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_fd == -1) {
cerr << "Failed to create socket" << endl;
return -1;
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(12345);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listen_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
cerr << "Failed to bind socket" << endl;
return -1;
}
if (listen(listen_fd, 5) == -1) {
cerr << "Failed to listen" << endl;
return -1;
}
int epoll_fd = epoll_create(MAX_EVENTS);
if (epoll_fd == -1) {
cerr << "Failed to create epoll" << endl;
return -1;
}
struct epoll_event ev, events[MAX_EVENTS];
ev.events = EPOLLIN; // 监听可读事件
ev.data.fd = listen_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &ev) == -1) {
cerr << "Failed to add listen socket to epoll" << endl;
return -1;
}
while (true) {
int nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
if (nfds == -1) {
cerr << "Failed to wait for epoll events" << endl;
break;
}
for (int i = 0; i < nfds; ++i) {
int fd = events[i].data.fd;
if (fd == listen_fd) { // 新连接
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int client_fd = accept(listen_fd, (sockaddr*)&client_addr, &len);
if (client_fd == -1) {
cerr << "Failed to accept client socket" << endl;
continue;
}
cout << "New client connected: " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port) << endl;
ev.events = EPOLLIN | EPOLLET; // 监听可读事件和边沿触发
ev.data.fd = client_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &ev) == -1) {
cerr << "Failed to add client socket to epoll" << endl;
close(client_fd);
}
} else { // 有数据可读
char buf[BUF_SIZE];
int nread = read(fd, buf, BUF_SIZE);
if (nread == -1) {
cerr << "Failed to read data from socket" << endl;
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL); // 删除该socket
close(fd);
} else if (nread == 0) {
cout << "Client disconnected" << endl;
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL); // 删除该socket
close(fd);
} else {
cout << "Received data from client: " << buf << endl;
write(fd, buf, nread); // 原样返回
}
}
}
}
close(epoll_fd);
close(listen_fd);
return 0;
评论