1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include <event2/event.h> #include <event2/bufferevent.h> #include <iostream> #include <cutils/sockets.h> #include <arpa/inet.h> #include <event2/buffer.h>
void read_cb(struct bufferevent *bev, void *ctx) { struct evbuffer *input = bufferevent_get_input(bev); size_t len = evbuffer_get_length(input); char *data = (char *) malloc(len + 1); evbuffer_remove(input, data, len); data[len] = '\0'; printf("Received: %s\n", data); free(data); }
void event_cb(struct bufferevent *bev, short events, void *ctx) { if (events & BEV_EVENT_ERROR) { perror("Error from bufferevent"); } if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) { bufferevent_free(bev); } }
void stdin_read_cb(evutil_socket_t fd, short events, void *arg) { struct bufferevent *bev = (struct bufferevent *) arg; char msg[1024]; if (fgets(msg, sizeof(msg), stdin)) { struct evbuffer *output = bufferevent_get_output(bev); evbuffer_add(output, msg, strlen(msg)); } else { event_base_loopbreak(bufferevent_get_base(bev)); } }
int main() { event_base *base = event_base_new(); if (!base) { std::cerr << "Error creating event base" << std::endl; return -1; }
sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = inet_addr("127.0.0.1"); sin.sin_port = htons(8080);
bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(bev, read_cb, NULL, event_cb, NULL); bufferevent_enable(bev, EV_READ | EV_WRITE); if (bufferevent_socket_connect(bev, (sockaddr *) &sin, sizeof(sin)) < 0) { std::cerr << "Error connecting to server" << std::endl; return -1; } struct event *ev_stdin = event_new(base, fileno(stdin), EV_READ | EV_PERSIST, stdin_read_cb, bev); event_add(ev_stdin, NULL);
event_base_dispatch(base);
bufferevent_free(bev); event_base_free(base);
return 0; }
|