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 70 71 72 73 74 75 76 77 78 79
| #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #include <event2/event.h> #include <event2/bufferevent.h> void read_cb(struct bufferevent *, void *); void write_cb(struct bufferevent *, void *); void events_cb(struct bufferevent *, short , void *); void send_cb(evutil_socket_t , short , void* ); int main() { struct event_base* base = event_base_new(); struct bufferevent* bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(8989); inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr); bufferevent_socket_connect(bev, (struct sockaddr*)&addr, sizeof(addr)); bufferevent_setcb(bev, read_cb, write_cb, events_cb, base); bufferevent_enable(bev, EV_READ); struct event *ev = event_new(base, STDIN_FILENO, EV_READ|EV_PERSIST, send_cb, bev); event_add(ev, NULL); event_base_dispatch(base); bufferevent_free(bev); event_base_free(base); }
void send_cb(evutil_socket_t fd, short what, void* arg) { char buf[1024] = {0}; read(fd, buf, sizeof(buf));
struct bufferevent *bev = (struct bufferevent*)arg; bufferevent_write(bev, buf, strlen(buf)+1); printf("客户端发送数据完毕\n"); }
void read_cb(struct bufferevent *bev, void *ctx) { char buf[1024]; memset(buf, 0, sizeof(buf)); bufferevent_read(bev, buf, sizeof(buf)); printf("接收到服务器回复的数据 : %s\n", buf); }
void write_cb(struct bufferevent *bev, void *ctx) { printf("数据被写入内核\n"); }
void events_cb(struct bufferevent *bev, short events, void *ctx) { struct event_base *base = (struct event_base*)ctx; if(events & BEV_EVENT_EOF) { printf("服务器断开了链接\n"); } else if(events & BEV_EVENT_ERROR) { printf("不可预期错误\n"); } else if(events & BEV_EVENT_CONNECTED) { printf("和服务器成功建立链接\n"); return; } event_base_loopbreak(base); }
|