EPOLL解决单个客户端同时连接多个服务端的问题

之前尝试过没有成功  改成协程了 

但是协程依赖于协程库 所以 重新改成EPOLL 今天试了下 成功了 

关键代码

#ifdef EPOLL

bool QMCY_APP::CreateEPOLL()
{

	m_epoll_fd = epoll_create1(0);
	if (m_epoll_fd < 0)
	{
		printf("epoll_create failed\n");
		return false;
	}

	return true;
}


bool QMCY_APP::DestroyEPOLL()
{
	if (m_epoll_fd > 0 ) 
	{
		close(m_epoll_fd);
	}

	return true;
}



bool QMCY_APP::Add2Epoll(std::shared_ptr  led,bool is_tcp)
{
	int fd;
	auto ip = led->NVR_GetIP().c_str();
	auto port = led->NVR_GetPort();


	struct sockaddr_in my_addr;
	//socklen_t peer_addr_size;


	if(is_tcp)
	{
		fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);		
	}
	else
	{
		fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, 0);	
	}



	if (fd == -1)
	{
		printf("Add2Epoll Create socket failed\n");
		return false;
	}

	memset(&my_addr, 0, sizeof(my_addr));
	my_addr.sin_family = AF_INET;
	my_addr.sin_addr.s_addr = inet_addr(ip);
	my_addr.sin_port = htons(port);

	int ret = connect(fd, (struct sockaddr*)&my_addr, sizeof(my_addr));

	if (ret == 0) {
		puts("connect successfully!");
		//return false;
	}

	if (errno != EINPROGRESS) printf("Add2Epoll success [%s:%d] \n",ip,port);


	struct epoll_event ev;
	
	ev.events = EPOLLOUT |EPOLLET |EPOLLIN;
	ev.data.fd = fd;

	if (epoll_ctl(m_epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1)
	{
		printf("epoll_ctl failed\n");
		return false;
	}

	m_led_all.insert(std::pair>(fd,led));
	led->NVR_ResetState();
	return true;
}


bool QMCY_APP::DelFromEPOLL()
{
	for(auto 

你可能感兴趣的:(服务器)