V
V
Vladislav Orlov2015-01-12 17:55:43
Notifications
Vladislav Orlov, 2015-01-12 17:55:43

Libevent as a tcp client - why does the event handler end with 1?

I decided to implement a tcp client on libevent. I understand a series of articles: www.ibm.com/developerworks/ru/library/l-Libevent3
I tried to use listing No. 1 from there:

#include <event2/event.h>
#include <event2/bufferevent.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void bufev_callback( struct bufferevent *buf_ev, short events, void *ptr )
{
    if( events & BEV_EVENT_CONNECTED )
    {
        printf( "Соединение установлено\n" );
        /* Здесь можно было бы выполнить и более полезные операции,
         * например, чтение или запись данных
         */
    }
    else if( events & BEV_EVENT_ERROR )
    {
        exit(-1);
        /* Перед принудительным завершением программы при необходимости
         * выполняются "спасательные действия" (освобождение памяти,
         * закрытие файлов и т.д.), если это возможно
         */
    }
}

int main( void )
{
    struct event_base *base;
    struct bufferevent *buf_ev;
    struct sockaddr_in sin;

    base = event_base_new();

    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( 7824 );

    buf_ev = bufferevent_socket_new( base, -1, BEV_OPT_CLOSE_ON_FREE );
    bufferevent_setcb( buf_ev, NULL, NULL, bufev_callback, NULL );

    if( bufferevent_socket_connect( buf_ev, (struct sockaddr *)&sin, sizeof(sin) ) < 0 )
    {
        /* Попытка установить соединение была неудачной */
        bufferevent_free( buf_ev ); /* сокет закроется автоматически; см. флаг при создании */
        return -1;
    }

    int result = event_base_dispatch( base );

    printf("event_base_dispatch: %d", result);
    return 0;
}


At the output I get:
Соединение установлено
event_base_dispatch: 1
Process finished with exit code 0


I can't figure out why the event handler ends returning 1 (according to the documentation it says that the function returns: 0 if successful, -1 if an error occurred, or 1 if no events were registered.). Help me understand why this behavior is that there are no registered events - did I add an event using bufferevent_socket_new?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question