c++ libevent demo

Server::Server(const char *ip, int port)
{
	//创建事件集合
	base = event_base_new();

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

	//创建监听对象
	listener = evconnlistener_new_bind(base, listener_cb, NULL, 
		LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, 10, (struct sockaddr *)&server_addr, 
			sizeof(server_addr));
	if (NULL == listener)
	{
		cout << "evconnlistener_new_bind error" << endl;
	}

	cout << "服务器初始化成功 开始监听客户端" << endl;
	event_base_dispatch(base);       //监听集合
}

//当有客户端发起连接的时候,会触发该函数
void Server::listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *addr, int socklen, void *arg)
{
	cout << "接受客户端的连接,fd = " << fd << endl;

	//创建工作线程来处理该客户端
	thread client_thread(client_handler, fd);
	client_thread.detach();    //线程分离,当线程运行结束后,自动释放资源
}

void Server::client_handler(int fd)
{
	//创建集合
	struct event_base *base = event_base_new();

	//创建bufferevent对象
	struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
	if (NULL == bev)
	{
		cout << "bufferevent_socket_new error" << endl;
	}

	//给bufferevent设置回调函数
	bufferevent_setcb(bev, read_cb, NULL, event_cb, NULL);

	//使能回调函数
	bufferevent_enable(bev, EV_READ);

	event_base_dispatch(base);    //监听集合(监听客户端是否有数据发送过来)

	event_base_free(base);
	cout << "线程退出、释放集合" << endl;
}

void Server::read_cb(struct bufferevent *bev, void *ctx)
{
	char buf[1024] = {0};
	int size = bufferevent_read(bev, buf, sizeof(buf));
	if (size < 0)
	{
		cout << "bufferevent_read error" << endl;
	}

	cout << buf << endl;

	Json::Reader reader;       //解析json对象
	Json::FastWriter writer;   //封装json对象
	Json::Value val;

	if (!reader.parse(buf, val))    //把字符串转换成 json 对象
	{
		cout << "服务器解析数据失败" << endl;
	}

	string cmd = val["cmd"].asString();

	if (cmd == "register")   //注册功能
	{
		server_register(bev, val);	
	}
	
}

void Server::event_cb(struct bufferevent *bev, short what, void *ctx)
{
	
}

Server::~Server()
{
	event_base_free(base);
}

void Server::server_register(struct bufferevent *bev, Json::Value val)
{
}


推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt

你可能感兴趣的:(c++,开发语言)