上一篇写了简单使用libevent的例子,本篇写一个高级一点的回显服务器程序,使用libevent提供的高级利器bufferevent,客户端程序请参考上篇文章。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#define MAX_BUF_SIZE 1024
void do_event_cb(struct bufferevent *bev, short event, void *arg)
{
if (event & BEV_EVENT_EOF)
{
printf("connection closed by peer, socket: %d ...\r\n",
bufferevent_getfd(bev));
}
else if (event & BEV_EVENT_ERROR)
{
printf("some error happened ...\r\n");
}
bufferevent_free(bev);
}
void do_read_cb(struct bufferevent *bev, void *arg)
{
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
int len = evbuffer_get_length(input);
if (len)
{
evbuffer_add_buffer(output, input);
}
}
void do_accept_cb(int fd, short events, void *arg)
{
evutil_socket_t sock;
struct sockaddr_in client;
int len;
sock = accept(fd, (struct sockaddr*)&client, &len);
if (sock < 0)
{
fprintf(stderr, "accept() error: errno %d --- %s\r\n",
errno, strerror(errno));
return;
}
evutil_make_socket_nonblocking(sock);
struct event_base *base = (struct event_base *)arg;
struct bufferevent *bev = bufferevent_socket_new(base, sock,
BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, do_read_cb, NULL, do_event_cb, arg);
bufferevent_enable(bev, EV_READ | EV_PERSIST);
}
int init_echo_server(int port)
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
fprintf(stderr, "socket() error: errno %d --- %s\r\n",
errno, strerror(errno));
return -1;
}
evutil_make_listen_socket_reuseable(sock);
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(port);
if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
fprintf(stderr, "bind() error: errno %d --- %s\r\n",
errno, strerror(errno));
goto error;
}
if (listen(sock, 32) < 0)
{
fprintf(stderr, "listen() error: errno %d --- %s\r\n",
errno, strerror(errno));
goto error;
}
struct event_base *base = event_base_new();
struct event *ev_listen = event_new(base, sock, EV_READ | EV_PERSIST,
do_accept_cb, base);
event_add(ev_listen, NULL);
event_base_dispatch(base);
event_base_free(base);
return 0;
error:
close(sock);
return -1;
}
int main(int argc, char **argv)
{
int port = 9999;
if (argc >= 2)
{
port = atoi(argv[1]);
if (port < 0 || port > 65535)
{
fprintf(stderr, "Invalid port ...\r\n");
return -1;
}
}
init_echo_server(port);
return 0;
}