linux c 使用epoll处理socket连接以及客户端读写入门

#include <sys/wait.h>
#include <stdint.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <sys/times.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>

/**
 * https://man7.org/linux/man-pages/man7/epoll.7.html

 The following system calls are provided to create and manage an
 epoll instance:

 • epoll_create(2) creates a new epoll instance and returns a file
 descriptor referring to that instance.  (The more recent
 epoll_create1(2) extends the functionality of epoll_create(2).)

 • Interest in particular file descriptors is then registered via
 epoll_ctl(2), which adds items to the interest list of the
 epoll instance.

 • epoll_wait(2) waits for I/O events, blocking the calling thread
 if no events are currently available.  (This system call can be
 thought of as fetching items from the ready list of the epoll
 instance.)

 */

#define MAX_EVENTS 10

int setnonblocking(int fd) {
	int flags;

	if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
		flags = 0;
	return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

void do_use_fd(int fd, char *buffer) {
	printf("do_use_fd \n");
	while (1) {
		int length = read(fd, buffer, 1023);
		if (length <= 0) {
			printf("read error \n");
			perror("read error");
			break;
		}
		buffer[length] = '\0';
		printf("%s", buffer);
		write(fd, buffer, length);
	}
}

int main() {
	char buffer[1024] = { 0 };
	int listenfd = 0;
	int conn_sock = 0;
	struct sockaddr_in address;
	int addrlen = sizeof(address);
	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	memset(&address, '0', addrlen);

	address.sin_family = AF_INET;
	address.sin_addr.s_addr = htonl(INADDR_ANY);
	address.sin_port = htons(8080);

	bind(listenfd, (struct sockaddr*) &address, addrlen);

	if (listen(listenfd, 3) < 0) {
		perror("listen");
		exit(EXIT_FAILURE);
	}

	int epollfd;
	struct epoll_event ev;
	struct epoll_event events[MAX_EVENTS];
	int nfds;
	epollfd = epoll_create1(0);
	if (epollfd == -1) {
		perror("epoll_create1");
		exit(EXIT_FAILURE);
	}

	ev.events = EPOLLIN;
	ev.data.fd = listenfd;

	if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &ev) == -1) {
		perror("epoll_ctl: listen_sock");
		exit(EXIT_FAILURE);
	}

	for (;;) {
		printf("epoll_wait \n");
		nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
		if (nfds == -1) {
			perror("epoll_wait");
			exit(EXIT_FAILURE);
		}
		printf("new msg \n");
		for (int n = 0; n < nfds; n++) {
			if (events[n].data.fd == listenfd) {
				conn_sock = accept(listenfd, (struct sockaddr*) &address,
						(socklen_t*) &addrlen);
				if (conn_sock < 0) {
					perror("accept");
					exit(EXIT_FAILURE);
				}
				setnonblocking(conn_sock);
				ev.events = EPOLLIN | EPOLLET;
				ev.data.fd = conn_sock;
				if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev) == -1) {
					perror("epoll_ctl: conn_sock");
					exit(EXIT_FAILURE);
				}
			} else {
				do_use_fd(events[n].data.fd, buffer);
			}
		}
	}
	shutdown(listenfd, SHUT_RDWR);
	return EXIT_SUCCESS;
}


测试 : telnet 127.0.0.1 8080
可以打开2个终端来测试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用epoll函数来实现高效的I/O多路复用,从而建立一个高性能的服务器。以下是一个简单的示例代码: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/epoll.h> #define MAX_EVENTS 10 int main(int argc, char *argv[]) { int listen_fd, conn_fd, epoll_fd, nfds, n, i; struct sockaddr_in serv_addr, cli_addr; socklen_t cli_len = sizeof(cli_addr); struct epoll_event ev, events[MAX_EVENTS]; // 创建监听套接字 if ((listen_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket error"); exit(EXIT_FAILURE); } // 设置地址重用 int optval = 1; setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); // 绑定地址 memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(8080); if (bind(listen_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) { perror("bind error"); exit(EXIT_FAILURE); } // 监听 if (listen(listen_fd, 10) == -1) { perror("listen error"); exit(EXIT_FAILURE); } // 创建epoll实例 if ((epoll_fd = epoll_create1(0)) == -1) { perror("epoll_create1 error"); exit(EXIT_FAILURE); } // 添加监听套接字到epoll实例中 ev.events = EPOLLIN; ev.data.fd = listen_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &ev) == -1) { perror("epoll_ctl error"); exit(EXIT_FAILURE); } // 循环等待事件 while (1) { nfds = epoll_wait(epoll_fd, events, MAX_EVENTS, -1); if (nfds == -1) { perror("epoll_wait error"); exit(EXIT_FAILURE); } // 处理所有事件 for (i = 0; i < nfds; i++) { if (events[i].data.fd == listen_fd) { // 有新连接 conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, &cli_len); if (conn_fd == -1) { perror("accept error"); exit(EXIT_FAILURE); } // 将新连接添加到epoll实例中 ev.events = EPOLLIN; ev.data.fd = conn_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, conn_fd, &ev) == -1) { perror("epoll_ctl error"); exit(EXIT_FAILURE); } } else { // 有数据可读 char buf[1024]; n = read(events[i].data.fd, buf, sizeof(buf)); if (n == -1) { perror("read error"); exit(EXIT_FAILURE); } else if (n == 0) { // 连接关闭 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, NULL) == -1) { perror("epoll_ctl error"); exit(EXIT_FAILURE); } close(events[i].data.fd); } else { // 回显数据 if (write(events[i].data.fd, buf, n) == -1) { perror("write error"); exit(EXIT_FAILURE); } } } } } return 0; } ``` 这个示例代码使用epoll实现了一个简单的回显服务器,可以在Linux下编译运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值