Implement a simple libevent server in Windows, windowslibevent
I recently learned about Libevent because I am using a windows system. Unfortunately, there are few programs that can be referenced in. After reading many blog articles. I found a simple Libevent Server program. A simple client program was found online to test the code. Make a record here today.
Libevent is indeed a very useful thing. It is still learning, and the multi-thread use of Libevent will be implemented in windows in the future. Today, we will first post what we have made for your reference. Compiled on vs2015.
By default, it is single-threaded (multithreading can be configured, if needed). Each thread has only one event base, it corresponds to a struct event_base struct (and the event manager attached to it) and is used to host a series of events hosted by schedule. It can be compared with the process management class of the operating system. Of course, it is simpler. When an event occurs, event_base will call the function bound to the event at the appropriate time (not necessarily immediately) (pass in some predefined parameters, and a parameter specified during binding) until the function is executed, other schedule events are returned.
// Create an event_base
Struct event_base * base = event_base_new ();
Assert (base! = NULL );
Event_base has a loop, which is blocked by epoll, kqueue, and other system calls until one or more events occur and then processes these events. Of course, these events will be bound to this event_base. Each event corresponds to a struct event, which can be a listener for one fd or POSIX semaphores (Here we only talk about fd, others can look at manual ). Use event_new to create and bind a struct event, and use event_add to enable it:
// Create and bind an event
Struct event * listen_event;
// Parameter: event_base, listening fd, event type and attribute, bound callback function, and parameters for the callback function
Listen_event = event_new (base, listener, EV_READ | EV_PERSIST, callback_func, (void *) base );
// Parameter: event, timeout (struct timeval * type, NULL indicates no timeout settings)
Event_add (listen_event, NULL );
Note: libevent supports the following events and attributes: (bitfield is used, so | is used to make them fit)
(A) EV_TIMEOUT: timeout
(B) EV_READ: the callback function is triggered as long as there is data in the network buffer.
(C) EV_WRITE: the callback function is triggered when only the data buffered by the network is written.
(D) EV_SIGNAL: POSIX semaphore. Refer to manual.
(E) EV_PERSIST: If this attribute is not specified, the event will be deleted after the callback function is triggered.
(F) EV_ET: Edge-Trigger Edge Trigger. For more information, see EPOLL_ET.
Then, you need to start the event_base loop to process the events. The cycle starts the event base dispatch, and the cycle continues until there are no more events to be concerned about, or the event_loopbreak ()/event_loopexit () function is encountered.
// Start the event Loop
Event_base_dispatch (base );
Next, pay attention to the callback function callback_func bound to the event: what is passed to it is a socket fd, an event type and attribute bit_field, And the last parameter passed to event_new (go to the above lines to review and pass event_base to it, in fact, it is more about allocating a struct, embedding all the relevant data, and then throwing it to event_new, which can be obtained here ). Its prototype is:
Typedef void (* event_callback_fn) (evutil_socket_t sockfd, short event_type, void * arg)
For a server, the above process is probably combined as follows:
1. listener = socket (), bind (), listen (), set nonblocking (fcntl can be used in POSIX systems, windows does not need to be set,
In fact, libevent provides a uniform packaging of evutil_make_socket_nonblocking)
2. Create an event_base
3. Create an event, host the socket to event_base, specify the event type to listen to, and bind the corresponding callback function (and parameters to be provided)
. For listener socket, you only need to listen to EV_READ | EV_PERSIST
4. Enable this event
5. Enter the event Loop
---------------
6. (asynchronous) when a client initiates a request, this callback function is called for processing.
/* Next, pay attention to the callback function callback_func bound to the event: what is passed to it is a socket fd, an event type and attribute bit_field, And the last parameter passed to event_new (go to the above lines to review and pass event_base to it, in fact, it is more about allocating a struct, embedding all the relevant data, and then throwing it to event_new, which can be obtained here ). */
Server code: Server. cpp
1 # include <WinSock2.h> 2 # include <stdlib. h> 3 # include <stdio. h> 4 # include <string. h> 5 # include <errno. h> 6 # include <event2/event. h> 7 # include <event2/bufferevent. h> 8 # include <iostream> 9 # include <cassert> 10 # pragma comment (lib, "ws2_32.lib") 11 # include <ws2tcpip. h> 12 # define LISTEN_PORT 9999 13 # define LIATEN_BACKLOG 32 14 using namespace std; 15 /************************************** *** **************************************** 16 * function declaration 17 *********************************** **************************************** * *****/18 // accept returns the function 19 void do_accept_cb (evutil_socket_t listener, short event, void * arg); 20 // read callback function 21 void read_cb (struct bufferevent * bev, void * arg ); 22 // error callback function 23 void error_cb (struct bufferevent * bev, short event, void * arg); 24 // write callback function 25 void Write_cb (struct bufferevent * bev, void * arg ); 26 /************************************** **************************************** * ** 27 * function body 28 ******************************** **************************************** * ********/29 // accept: return the function 30 void do_accept_cb (evutil_socket_t listener, short event, void * arg) 31 {32 // input event_base pointer 33 struct event_base * base = (struct event_base *) arg; 34 // Socket descriptor 35 evutil_socket_t fd; 36 // declare address 37 struct sockaddr_in sin; 38 // address length declaration 39 socklen_t slen = sizeof (sin ); 40 // receiving client 41 fd = accept (listener, (struct sockaddr *) & sin, & slen); 42 if (fd <0) 43 {44 perror ("error accept"); 45 return; 46} 47 printf ("ACCEPT: fd = % u \ n", fd ); 48 /// register a bufferevent_socket_new event 49 struct bufferevent * bev = bufferevent_socket_new (base, fd, BEV_OPT_CLOSE_ON_FR EE); 50 // You can call back the function 51 bufferevent_setcb (bev, read_cb, NULL, error_cb, arg ); 52 // set the property of the event 53 bufferevent_enable (bev, EV_READ | EV_WRITE | EV_PERSIST ); 54} 55 // read callback function 56 void read_cb (struct bufferevent * bev, void * arg) 57 {58 # define MAX_LINE 256 59 char line [MAX_LINE + 1]; 60 int n; 61 // find socket fd 62 evutil_socket_t fd = bufferevent_getfd (bev) by passing in the bev parameter; 63 // 64 while (n = bufferevent _ Read (bev, line, MAX_LINE) 65 {66 line [n] = '\ 0'; 67 printf ("fd = % u, read line: % s \ n ", fd, line); 68 // return the obtained data to the client 69 bufferevent_write (bev, line, n ); 70} 71} 72 // error callback function 73 void error_cb (struct bufferevent * bev, short event, void * arg) 74 {75 // find socket fd 76 evutil_socket_t fd = bufferevent_getfd (bev); 77 // cout <"fd =" <fd <endl; 78 if (event & BEV_EVENT_TIMEOUT) 79 {8 0 printf ("Timed out \ n"); // if bufferevent_set_timeouts () called 81} 82 else if (event & BEV_EVENT_EOF) 83 {84 printf ("connection closed \ n"); 85} 86 else if (event & BEV_EVENT_ERROR) 87 {88 printf ("some other error \ n "); 89} 90 bufferevent_free (bev); 91} 92 // write callback function 93 void write_cb (struct bufferevent * bev, void * arg) 94 {95 char str [50]; 96 // find the socket fd 97 evutil_socket_t fd by passing in the bev Parameter = Bufferevent_getfd (bev); 98 // cin> str; 99 printf ("input data! "); 100 scanf_s (" % d ", & str); 101 bufferevent_write (bev, & str, sizeof (str); 102} 103 104 int main () 105 {106 int ret; 107 evutil_socket_t listener; 108 WSADATA Ws; 109 // Init Windows Socket110 if (WSAStartup (MAKEWORD (2, 2), & Ws )! = 0) 111 {112 return-1; 113} 114 listener = socket (AF_INET, SOCK_STREAM, 0); 115 assert (listener> 0); 116 evutil_make_listen_socket_reuseable (listener ); 117 struct sockaddr_in sin; 118 sin. sin_family = AF_INET; 119 sin. sin_addr.s_addr = 0; 120 sin. sin_port = htons (LISTEN_PORT); 121 if (bind (listener, (struct sockaddr *) & sin, sizeof (sin) <0) {122 perror ("bind "); 123 return 1; 124} 125 if (listen (listener, 1000) <0) {126 perror ("listen"); 127 return 1; 128} 129 printf ("Listening... \ n "); 130 evutil_make_socket_nonblocking (listener); 131 struct event_base * base = event_base_new (); 132 assert (base! = NULL); 133 struct event * listen_event; 134 listen_event = event_new (base, listener, EV_READ | EV_PERSIST, do_accept_cb, (void *) base); 135 event_add (listen_event, NULL ); 136 event_base_dispatch (base); 137 printf ("The End. "); 138 return 0; 139}
Client code: Client. cpp
1/******* client program. c ************/2 # define _ WINSOCK_DEPRECATED_NO_WARNINGS 3 # define _ CRT_SECURE_NO_WARNINGS 4 # include <stdlib. h> 5 # include <stdio. h> 6 # include <errno. h> 7 # include <string. h> 8 # include <winsock2.h> 9 # include <ws2tcpip. h> 10 # include <iostream> 11 12 # pragma comment (lib, "ws2_32.lib") 13 int main (int argc, char * argv []) 14 {15 WSADATA Ws; 16 // Init Windows Socket17 if (WSAStartu P (MAKEWORD (2, 2), & Ws )! = 0) 18 {19 return 0; 20} 21 int sockfd; 22 char buffer [1024]; 23 struct sockaddr_in server_addr; 24 struct hostent * host; 25 int portnumber, nbytes; 26 27 if (host = gethostbyname ("127.0.0.1") = NULL) 28 {29 fprintf (stderr, "Gethostname error \ n"); 30 exit (1 ); 31} 32 33 if (portnumber = atoi ("9999") <0) 34 {35 fprintf (stderr, "Usage: % s hostname portnumber \ a \ n ", argv [0]); 36 exit (1); 37} 38 39/* the customer program starts to establish the sockfd descriptor */40 if (sockfd = socket (AF_INET, SOCK_STREAM, 0) =-1) 41 {42 fprintf (stderr, "Socket Error: % s \ a \ n", strerror (errno); 43 exit (1 ); 44} 45 46/* customer program fill in server information */47 memset (& server_addr, 0, sizeof (server_addr); 48 server_addr.sin_family = AF_INET; 49 server_addr.sin_port = htons (portnumber); 50 server_addr.sin_addr = * (struct in_addr *) host-> h_addr ); 51 52/* client program initiates Connection Request */53 if (connect (sockfd, (struct sockaddr *) (& server_addr), sizeof (struct sockaddr) =-1) 54 {55 fprintf (stderr, "Connect Error: % s \ a \ n", strerror (errno); 56 exit (1); 57} 58 59 while (true) 60 {61 char MESSAGE [] = "hello server .. \ n "; 62 // bufferevent_write (buf_ev, MESSAGE, strlen (MESSAGE); 63 // 64 if (-1 = (: send (sockfd, MESSAGE, strlen (MESSAGE), 0) 65 {66 printf ("the net has a error occured .. "); 67 break; 68} 69 70 if (nbytes = recv (sockfd, buffer,) =-1) 71 {72 fprintf (stderr," read error: % s \ n ", strerror (errno); 73 exit (1); 74} 75 76 buffer [nbytes] = '\ 0'; 77 printf (" I have received: % s \ n ", buffer); 78 memset (buffer, 0, 1024); 79 80 Sleep (2 ); 81 82} 83/* end communication */84 closesocket (sockfd); 85 exit (0); 86 87 return 0; 88}