DSL
libevent.h
1 //@AUTOHEADER@BEGIN@
2 /***********************************************************************\
3 | Drift Standard Libraries v1.01 |
4 | Copyright 2010-2022 Drift Solutions / Indy Sams |
5 | Docs and more information available at https://www.driftsolutions.dev |
6 | This file released under the 3-clause BSD license, |
7 | see included DSL.LICENSE.TXT file for details. |
8 \***********************************************************************/
9 //@AUTOHEADER@END@
10 
11 #ifndef __DRIFT_LIBEVENT_H__
12 #define __DRIFT_LIBEVENT_H__
13 
14 #include <drift/sockets3.h>
15 #include <set>
16 #include <event2/event.h>
17 
18 #if defined(DSL_DLL) && defined(WIN32)
19  #if defined(DSL_LIBEVENT_EXPORTS)
20  #define DSL_LIBEVENT_API extern "C" __declspec(dllexport)
21  #define DSL_LIBEVENT_API_CLASS __declspec(dllexport)
22  #else
23  #define DSL_LIBEVENT_API extern "C" __declspec(dllimport)
24  #define DSL_LIBEVENT_API_CLASS __declspec(dllimport)
25  #endif
26 #else
27  #define DSL_LIBEVENT_API DSL_API_VIS
28  #define DSL_LIBEVENT_API_CLASS DSL_API_VIS
29 #endif
30 
31 struct DSL_SOCKET_LIBEVENT;
32 
33 typedef void (*dsl_sockets_event_callback) (DSL_SOCKET_LIBEVENT * sock, short flags);
34 
36  /* User-accesible Fields */
37  DSL_SOCKET * sock;
38  void * user_ptr;
39 
40  /* Private Fields */
41  event * evread;
42  event * evwrite;
43  bool connecting;
44  dsl_sockets_event_callback read_cb;
45  dsl_sockets_event_callback write_cb;
46  dsl_sockets_event_callback connect_cb;
47 };
48 
49 class DSL_LIBEVENT_API_CLASS DSL_Sockets_Events {
50  protected:
51  private:
52  DSL_Sockets3_Base * socks = NULL;
53  event_base * evbase = NULL;
54  set<DSL_SOCKET_LIBEVENT *> sockets;
55  public:
58  event_base * GetEventBase() { return evbase; }
59 
60  int LoopWithFlags(int flags=0); // can be 0, EVLOOP_ONCE and/or EVLOOP_NONBLOCK
61  int LoopWithTimeout(int timeout);
62  void LoopBreak();
63 
64  DSL_SOCKET_LIBEVENT * Add(DSL_SOCKET * sock, dsl_sockets_event_callback read_cb = NULL, dsl_sockets_event_callback write_cb = NULL, dsl_sockets_event_callback connect_cb = NULL, void * user_ptr = NULL, bool persist_recv = true, bool persist_write = false);
65  void Remove(DSL_SOCKET_LIBEVENT * s, bool close = false); // Removes the socket from libevents leaving it otherwise untouched, optionally closes the socket in the parent DSL_Sockets
66 
67  void EnableRecv(DSL_SOCKET_LIBEVENT * s, int timeout = 0);
68  void EnableWrite(DSL_SOCKET_LIBEVENT * s, int timeout = 0);
69  void DisableRecv(DSL_SOCKET_LIBEVENT * s);
70  void DisableWrite(DSL_SOCKET_LIBEVENT * s);
71 
72  DSL_SOCKET_LIBEVENT * AddTimer(dsl_sockets_event_callback cb, bool persist = true, void * user_ptr = NULL);
73  // use EnableRecv/DisableRecv to enable/disable timer
74  void FreeTimer(DSL_SOCKET_LIBEVENT * timer);
75 };
76 
77 #endif // __DRIFT_LIBEVENT_H__