libevent的事件簡單測試

#include <cstdio>
#include <event2/event.h>
#include <iostream>
#include <cstring>
#include <thread>

using namespace std;


struct timeval timeout = { 10, 0 };

static void
closed_cb(evutil_socket_t fd, short event, void *arg)
{
	if (EV_TIMEOUT & event) {
		printf("%s: Timeout!\n", __func__);
		exit(1);
	}

	if (EV_CLOSED & event) {
		printf("%s: detected socket close with success\n", __func__);
		return;
	}

	if (EV_READ & event) {
		char buf[1024] = { 0 };

		auto len = recv(fd, buf, 1023, 0);

		if (len > 0) {

			cout << "client say: " << buf << endl;
		}
	}
}

int main()
{
	event_base* base;
	event_config *cfg = event_config_new();;
	event *ev;
	const char *test = "test string";
	evutil_socket_t pair[2];

	event_config_require_features(cfg, EV_FEATURE_EARLY_CLOSE);
	base = event_base_new_with_config(cfg);
	event_config_free(cfg);
	if (!base) {
		return 0;
	}
	if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
		return (1);
	ev = event_new(base, pair[1], EV_CLOSED | EV_TIMEOUT | EV_READ | EV_PERSIST, closed_cb, event_self_cbarg());
	event_add(ev, &timeout);

	// 測試關閉一端,然後查看另外一端的響應
	//this_thread::sleep_for(5s);
	//shutdown(pair[0], SHUT_WR);

	// 測試寫入一端,然後在另外一端讀取
	this_thread::sleep_for(3s);
	if (send(pair[0], test, (int)strlen(test) + 1, 0) < 0)
		return (1);





	event_base_dispatch(base);
	event_base_free(base);
    return 0;
}

如果要消除死循環的打印,只要在事件處理函數中接收數據或者釋放資源即可,因爲默認是水平觸發

 

 

發佈了1050 篇原創文章 · 獲贊 45 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章