title: How to detect a client gets connected to the server using Libevent
body: <p>I am writing program that sets up a localhost server and a localhost client using <code>libevent</code>. And I need to know when the client gets connected to the server. Libevent provides six event signals for event callback, which are <code>BEV_EVENT_READING</code>, <code>BEV_EVENT_WRITING</code>, <code>BEV_EVENT_ERROR</code>, <code>BEV_EVENT_TIMEOUT</code>, <code>BEV_EVENT_EOF</code>, and <code>BEV_EVENT_CONNECTED</code>. Basically I wanna the client enter the event loop and keep waiting server to be online. If I simply run client program without server online, I sometimes get both <code>BEV_EVENT_READING</code> and <code>BEV_EVENT_CONNECTED</code> flags. The error for <code>BEV_EVENT_READING</code> is <code>connection refused</code> which makes senses since the server is offline. However, the flag <code>BEV_EVENT_CONNECTED</code> in this case is also set and the program immediately leaves even though I dispatch it. Below is the code piece</p>
  
  <pre><code>address.sin_family = AF_INET;
  address.sin_addr.s_addr = inet_addr("127.0.0.1");
  address.sin_port = htons(7777);
  buffev_ptr = bufferevent_socket_new(_evbase_ptr, -1, BEV_OPT_CLOSE_ON_FREE);
  
  bufferevent_setcb(buffev_ptr, myread, mywrite, mysignal, NULL);
  bufferevent_enable(buffev_ptr, EV_READ | EV_WRITE);
  
  bufferevent_socket_connect(buffev_ptr, (sockaddr_pt)&amp;address, sizeof(address));
  </code></pre>
  
  <p>So for the <code>mysignal</code> callback, what should I exactly write in order to deal with the situation where the client gets connected?</p>
  
  <pre><code>void_t Client::mysignal(buffev_pt bev, short flag, void_pt user_data) {
  
    // An event occurred during a read operation on the bufferevent.
    if(flag &amp; BEV_EVENT_READING) {
    }
  
    // An event occurred during a write operation on the bufferevent.
    if(flag &amp; BEV_EVENT_WRITING) {
    }
  
    // An error occurred during a bufferevent operation.
    if(flag &amp; BEV_EVENT_ERROR) {
    }
  
    // A timeout expired on the bufferevent.
    if(flag &amp; BEV_EVENT_TIMEOUT) {
    }
  
    // We got an end-of-line indication on the bufferevent.
    if(flag &amp; BEV_EVENT_EOF) {
    }
  
    // We finished a requested connection on the bufferevent.
    if(flag &amp; BEV_EVENT_CONNECTED) {
    }
  }
  </code></pre>
  
  <p>The <code>BEV_EVENT_CONNECTED</code> and <code>BEV_EVENT_ERROR</code> might happen simultaneously if I run the client program without server online. I was assuming that <code>BEV_EVENT_CONNECTED</code> will be only set when client get connected to the server but it seems not.</p>