The method of libevent Business data processing
This article mainly introduces "libevent business data processing method". In daily operation, I believe many people have doubts about libevent business data processing method. The editor consulted various materials and sorted out simple and easy operation methods. I hope to help you answer the doubts of "libevent business data processing method"! Next, please follow the small series to learn together!
The main structure of a loop is generally as follows:
while (! m_bQuitFlag)
{
epoll_or_select_func();
handle_io_events();
handle_other_things();
}
For some applications where the business logic processing is relatively simple and not too time-consuming, the handle_io_events() method can also be used to directly process the business in addition to receiving and sending data, that is, its structure is as follows:
void handle_io_events()
{
//send and receive data
recv_or_send_data();
//unpack and process data
decode_packages_and_process();
}
The recv_or_send_data() method calls the send/recv API to send and receive actual network data. Take receiving data as an example. After receiving the data and storing it in the receiving buffer, unpacking processing is performed next, and then business processing is performed, such as a login data packet, whose business is to verify whether the login account password is correct, record its login behavior, and so on. From the point of view of the program function call stack, these business processing logic are actually processed directly in the network sending and receiving data threads. What I mean is that the network thread calls the handle_io_events() method, the handle_io_events() method calls the decode_packages_and_process() method, and the decode_packages_and_process() method does the specific business logic processing.
It should be noted that in order to decouple the network layer from the business layer, the network layer usually provides interfaces for callback functions that we point to specific business processing functions. Take the usage of the libevent network library as an example:
int main(int argc, char **argv)
{
struct event_base *base;
struct evconnlistener *listener;
struct event *signal_event;
struct sockaddr_in sin;
base = event_base_new();
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
//listener_cb is our custom callback function
listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
(struct sockaddr*)&sin,
sizeof(sin));
if (! listener) {
fprintf(stderr, "Could not create a listener!\ n");
return 1;
}
//signal_cb is our custom callback function
signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);
if (! signal_event || event_add(signal_event, NULL)