注意:这篇文章上次更新于1421天前,文章内容可能已经过时。
This article was last updated1421 days ago, the content may be outdated.
写一个服务器程序包括以下几个步骤:
- socket
- bind
- listen
- accept
在 libevent 中,将上面几个函数都封装在了一起,即 evconnlistener_new_bind 函数。因为做了这么多封装,所以该函数的参数也特别多。
该函数被声明在 listener.h 中。其函数原型如下。
Writing a server program includes the following steps:
- socket
- bind
- listen
- accept
In libevent, the functions above are all wrapped together in the evconnlistener_new_bind function. Because of all this wrapping, this function also has a particularly large number of parameters.
This function is declared in listener.h. Its prototype is as follows.
1 | /** |
可以看到该函数的第一个参数需要一个事件集合,因此,在调用该函数之前应该先创建一个事件集合。通过 event_base_new 函数。即
It can be seen that the first parameter of this function requires an event base, so before calling this function, an event base should be created first, via the event_base_new function. That is:
1 | struct event_base* base = event_base_new(); |
第二个参数需要一个回调函数,当有一个新的连接到来时会调用该回调函数,如果将该回调函数设置为 NULL, 那么就不会做任何处理。
回调函数的类型是evconnlistener_cb,声明如下:
The second parameter requires a callback function, which is invoked when a new connection arrives. If this callback function is set to NULL, then nothing will be done.
The type of the callback function is evconnlistener_cb, declared as follows:
1 | /**@file event2/listener.h |
flags 参数的可供选项也在 listener.h 中进行了介绍,主要包括以下几个。
The available options for the flags parameter are also introduced in listener.h, mainly including the following.
1 | /** Flag: Indicates that we should not make incoming sockets nonblocking |
剩下的其他参数都是常规操作了。
创建一个服务器需要用到的一些基本函数参考下面的例子。
The remaining parameters are all routine operations.
Some basic functions needed to create a server are shown in the example below.
1 |
|


