src/Network/Reactor.hh
author terom
Tue, 16 Dec 2008 23:21:26 +0000
changeset 380 d193dd1d8a7e
child 386 2f019ecb4aa9
permissions -rw-r--r--
new NetworkReactor, fix everything to actually work
#ifndef NETWORK_REACTOR_HH
#define NETWORK_REACTOR_HH

// forward-declare
class NetworkReactor;

/**
 * Events to poll for
 */
enum NetworkPollBit {
    POLL_READ       = 0x01,
    POLL_WRITE      = 0x02,
};

/**
 * Poll event bitmask of NetworkPollBit's
 */
typedef int NetworkPollMask;

#include "Socket.hh"
#include "Error.hh"

/*
 * Platform-specific includes
 */
#ifndef WIN32
    // linux
    #include <sys/select.h>
#else
    #error "This network code won't compile on win32 :)"
#endif

#include <list>

/**
 * A Reactor manages a set of NetworkSockets, providing readyness notification and a poll method
 */
class NetworkReactor {
    protected:
        std::list<NetworkSocket*> sockets;

    public:
        /**
         * Construct the empty reactor
         */
        NetworkReactor (void);

        /**
         * Our static global reactor
         */
        static NetworkReactor *current;

        /**
         * Add a NetworkSocket to our list of sockets. The desired notification states are fetched directly from the
         * socket itself.
         *
         * @param socket the socket to watch
         */
        void add_socket (NetworkSocket *socket) { sockets.push_back(socket); }

        /**
         * Remove a NetworkSocket from our list of sockets.
         *
         * @param socket the socket to stop watching
         */
        void remove_socket (NetworkSocket *socket) { sockets.remove(socket); }

        /**
         * Poll our sockets and drive any I/O, optionally sleeping for the given timeout. This is efficient if our
         * sockets list is empty.
         */
        void poll (timeval *timeout = NULL);
};

/**
 * Reactor error
 */
class NetworkReactorError : public NetworkErrno {
    public:
        NetworkReactorError (std::string op) : NetworkErrno(op) { }
};

#endif