[Libevent-users] Closing connection after bufferevent_write

Richard Crowley richard at opendns.com
Wed Apr 16 11:58:12 EDT 2008


I am using an event_dispatch() loop as the basis for a server listening 
on a socket and would like to terminate connections forcefully from the 
server.  The ideal flow would be: listen, client connects, event loop 
dispatches to my bufferevent where I accept the connection, the read 
callback is called and a response is given to the bufferevent, and the 
connection is closed (of course the main socket is still listening).

Here is some stripped-down sample code illustrating my code structure so 
far.  In the on_read() function, I read from the client's request, 
compute a response and write the response using bufferevent_write().  Is 
there a way to close the connection after that data is written? 
Currently I'm using special header and footer markers in the response 
data so the client can figure out when the response has ended and close 
the connection itself.  However, it would be nice if the server could 
close the connection so I won't have to have this logic in the client.

void on_read(struct bufferevent * bev, void * arg) {
     // ...
     char buf[4096];
     size_t len = bufferevent_read(bev, (void *)buf, 4096);
     // ...

     bufferevent_write(bev, "foo\n", 4);
     // *** I would like to close the connection after this write

}

void on_accept(int fd, short ev, void * arg) {
     // ...
     struct client * client = calloc(1, sizeof(struct client));
     if (!client) {
         fprintf(stderr, "Error: Call to calloc failed.\n");
         exit(1);
     }
     client->fd = client_fd;
     client->buf_ev = bufferevent_new(client_fd,
         on_read, on_write, on_error, client);
     bufferevent_enable(client->buf_ev, EV_READ);
}

int main(int argc, char * * argv) {
     // ...
     struct event ev_accept;
     event_set(&ev_accept, listen_fd, EV_READ|EV_PERSIST, on_accept, 0);
     event_add(&ev_accept, 0);
     event_dispatch();
     return 0;
}

Any help you can offer would be most appreciated.  Thanks,

Richard
richard at opendns.com


More information about the Libevent-users mailing list