Last active
February 13, 2020 16:21
-
-
Save optman/437fae08153624e95ccfe76c9cd1476c to your computer and use it in GitHub Desktop.
libevent https demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <event2/bufferevent_ssl.h> | |
#include <event2/bufferevent.h> | |
#include <event2/buffer.h> | |
#include <event2/event.h> | |
#include <event2/dns.h> | |
#include <openssl/ssl.h> | |
#include <iostream> | |
using namespace std; | |
const char* uri = "/"; | |
const char* host = "www.google.com"; | |
unsigned short port = 443; | |
static void request(bufferevent* bev){ | |
cout << "request" << endl; | |
auto out = bufferevent_get_output(bev); | |
evbuffer_add_printf(out, "GET %s HTTP/1.1\r\n", uri); | |
evbuffer_add_printf(out, "Host:%s:%d\r\n",host, port); | |
evbuffer_add_printf(out, "Connection:close\r\n"); | |
evbuffer_add_printf(out, "\r\n"); | |
} | |
static void read_cb(bufferevent* bev, void* ptr){ | |
cout << "read cb" << endl; | |
auto input = bufferevent_get_input(bev); | |
auto data_len = evbuffer_get_length(input); | |
unsigned char* data = evbuffer_pullup(input, -1); | |
cout << "data len " << data_len << endl; | |
cout << (const char*)data; | |
evbuffer_drain(input, data_len); | |
} | |
static void write_cb(bufferevent* bev, void* ptr){ | |
cout << "write cb" << endl; | |
} | |
static void event_cb(bufferevent* bev, short events, void* ptr){ | |
if(events & BEV_EVENT_CONNECTED){ | |
cout << "connected" << endl; | |
request(bev); | |
}else{ | |
cout << "diconnected " << events << endl; | |
} | |
} | |
static void init_ssl(){ | |
SSL_library_init(); | |
OpenSSL_add_all_algorithms(); | |
} | |
int main(){ | |
init_ssl(); | |
auto ssl_ctx = SSL_CTX_new(SSLv23_method()); | |
auto base = event_base_new(); | |
auto ssl = SSL_new(ssl_ctx); | |
SSL_set_tlsext_host_name(ssl, host); //enable SNI | |
auto bev = bufferevent_openssl_socket_new(base, -1, ssl, BUFFEREVENT_SSL_CONNECTING, | |
BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS); //auto free ssl when bev free | |
bufferevent_setcb(bev, read_cb, write_cb, event_cb, NULL); | |
bufferevent_socket_connect_hostname(bev, NULL, AF_INET, host, port); | |
event_base_dispatch(base); | |
bufferevent_free(bev); | |
event_base_free(base); | |
SSL_CTX_free(ssl_ctx); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
build on bufferevent, not evhttp.