C++ libevent 搭建服务器代码
时间: 2023-08-08 15:08:00 浏览: 144
以下是一个简单的 C++ libevent 服务器代码示例:
```cpp
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <string>
#include <iostream>
using namespace std;
void onRead(bufferevent *bev, void *ctx) {
char msg[4096];
size_t len = bufferevent_read(bev, &msg, sizeof(msg));
msg[len] = '\0';
cout << "Received message: " << msg << endl;
bufferevent_write(bev, "Server received the message.", 30);
}
void onAccept(evconnlistener *listener, evutil_socket_t fd, sockaddr *addr, int socklen, void *ctx) {
event_base *base = evconnlistener_get_base(listener);
bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, onRead, nullptr, nullptr, nullptr);
bufferevent_enable(bev, EV_READ | EV_WRITE);
}
int main() {
event_base *base = event_base_new();
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(8888);
evconnlistener *listener = evconnlistener_new_bind(base, onAccept, nullptr, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1, (sockaddr *)&sin, sizeof(sin));
event_base_dispatch(base);
return 0;
}
```
这个服务器监听 8888 端口,并在接收到客户端的连接请求时响应。当收到客户端的消息时,它将输出消息并回复 "Server received the message."。
在编译时需要添加如下链接库:
```
-lpthread -levent -levent_core -levent_extra
```
阅读全文