【Linux网络编程】基于TCP流 I/O多路转接(poll) 的高性能http服务器

本文介绍了一个基于poll实现的简易Web服务器项目。该服务器能够响应客户端请求,并发送简单的HTML内容作为回应。通过此示例,读者可以了解如何利用poll进行事件驱动编程,以及基本的网络编程知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



服务器比较简陋,为了学习poll的使用,只向客户端回写一条html语句。启动服务器后,浏览器发起请求,服务端向浏览器写回html,响应字符串,然后可以看到,浏览器解析并显示 Hello Poll!.


启动服务端:


用浏览器访问:


浏览器解析出字符串:



完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h> 
#include <poll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>


#define POLLFD_SIZE 1024 /* struct pollfd 结构体数组最大上限 */



/* 关心描述符集事件数组*/
struct pollfd array_pollfd[POLLFD_SIZE];

/* 结构体成员详情
struct pollfd 
{
	int fd;        // 关心的描述符
	short events;  // 关心的事件
	short revents; // 发生的事件
};
*/

/* 获取一个监听连接的sockfd */
int run_getsockfd(const char*ip, int port);

/* 执行poll检测 */
void run_poll(int listen_sockfd);

/* 响应客户端的连接,并添加新的描述符到关心事件中 */
void run_accept(int listen_sock);

/* 当与客户端连接的描述符有事件就绪时,做出响应 */
void run_action( int index);

int main(int argc, char **argv)
{
	if(argc != 3)
	{
		printf("usage: [server_ip] [server_port]");
		return 1;
	}

	int listen_sockfd = run_getsockfd(argv[1], atoi(argv[2]));

	run_poll(listen_sockfd);

	return 0;
}


/* 调用poll 并检测返回事件 */
void run_poll(int listen_sockfd)
{
	/* 将负责监听连接的sockfd注册事件 */
	array_pollfd[0].fd = listen_sockfd;
	array_pollfd[0].events = POLLIN;

	/* 初始化数组中的描述符 */
	int idx_init = 1;
	for(; idx_init < POLLFD_SIZE; ++idx_init)
	{
		array_pollfd[idx_init].fd = -1;
	}
	int timeout = 1000; /* 设定一秒后超时 */


	while(1)
	{
		int ret_poll = poll(array_pollfd,  POLLFD_SIZE, timeout);

		if(ret_poll == 0)        /* 超时    */
			printf("timeout\n");
		else if(ret_poll < 0)    /* 执行出错*/
			perror("poll()");
		else
		{/* 有关心的事件就绪  */

	    	/* 遍历数组,轮询检测poll的结果  */
	    	int idx_check = 0;
	    	for(idx_check = 0; idx_check < POLLFD_SIZE; ++idx_check)
	    	{
				if(idx_check == 0 && array_pollfd[0].revents & POLLIN)
				{/* listen_sockfd 读事件就绪 */
					run_accept(listen_sockfd); 
				}
				else if(idx_check != 0)
				{/* 与客户端连接的sockfd 有事件就绪 */
					run_action(idx_check);
				}
			}
		}
	} // end while 1
}


/* 当与客户端连接的描述符有事件就绪时,做出响应 */
void run_action( int index)
{
	if(array_pollfd[index].revents & POLLIN)
	{/* 客户端读事件发生 */
		char buf[1024];          /* 存储从客户端读来的消息 */ 
		memset(buf, 0, sizeof(buf));
		ssize_t s = read(array_pollfd[index].fd, buf, sizeof(buf)-1);
		if(s > 0)
		{
			buf[s-1] = '\0';
			printf("client say$ %s \n", buf);
			array_pollfd[index].events = POLLOUT;
		}
		else if( s <= 0)
		{
			printf("client quit!\n");
			close(array_pollfd[index].fd);
			array_pollfd[index].fd = -1;
		}

	}
	else if (array_pollfd[index].revents & POLLOUT)
	{/* 客户端写事件发生 */
		/* 使用浏览器测试,写回到客户端,浏览器会解析字符串,显示 Hellp Epoll! */
		const char* msg = "HTTP/1.1 200 OK\r\n\r\n<html><br/><h1>Hello poll!</h1></html>";
		write(array_pollfd[index].fd, msg, strlen(msg));	
		close(array_pollfd[index].fd);
		array_pollfd[index].fd = -1;
	}
}


/* 响应客户端的连接,并添加新的描述符到关心事件中 */
void run_accept(int listen_sock)
{
	struct sockaddr_in cliaddr;
	socklen_t clilen = sizeof(cliaddr);

	int new_sock = accept(listen_sock, (struct sockaddr*)&cliaddr, &clilen);
	if( new_sock < 0)
	{
		perror("accept");
		return ;
	}

	printf("与客户端连接成功: ip %s port %d \n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
	/* 将新socket描述符添加到数组中 */
	int idx_find = 1;
	for(; idx_find < POLLFD_SIZE; ++idx_find)
	{
		if(array_pollfd[idx_find].fd < 0)
		{
			array_pollfd[idx_find].fd = new_sock;
			array_pollfd[idx_find].events = POLLIN ;
			break;
		}
	}	
	if(idx_find == POLLFD_SIZE)
	{
		perror("连接超出最大限度,add array_pollfd[]");
		return;
	}

}

/* 获取一个监听socket */
int run_getsockfd(const char* ip, int port)
{
	int sock = socket(AF_INET, SOCK_STREAM, 0);
	if( sock < 0){
		perror("socket()");
		exit(1);
	}

	int opt = 1;
	setsockopt(sock , SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	struct sockaddr_in server;
	bzero(&server, sizeof(server));
	server.sin_addr.s_addr = inet_addr(ip);
	server.sin_port = htons(port);
	server.sin_family = AF_INET;

	if(bind(sock, (struct sockaddr *)&server, sizeof(server) ) < 0){
		perror("bind()");
		exit(2);
	}

	if(listen(sock, 5) < 0){
		perror("listen()");
		exit(3);
	}

	return sock;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值