// This file is part of Timmi. // // Timmi is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. #ifndef TCPSERVER_HH #define TCPSERVER_HH #include #include #include #include class TCPServer { public: TCPServer(); ~TCPServer(); // Binds the listening socket - other functions shouldn't be // called before binding. Returns true if binding succeeded. bool bind_socket(int port); // Wait for event or error for timeout milliseconds (-1 == forever) // Return false if timeouted bool wait_for_event(int timeout = -1) const; // Handle any new events void do_events(); // Find TCPSocket by fd TCPSocket *find_socket(int fd) const; // Send line to a client void send_line(int fd, std::string line); void send_line(TCPSocket &socket, std::string line); // Transmit a line to all connected clients void send_to_all(std::string line); // Default main loop handler // Waits for events without timeout and then handles them virtual void mainloop(); // New connection handler to be overridden // Default one prints debug message with level INFO virtual void handle_connection(TCPSocket &socket); // Line reception handler to be overridden // Default one prints debug message with level VERBOSE virtual void handle_line(TCPSocket &socket, std::string line); // Disconnection handler. // Overridden handlers must call the default one last. // It removes the socket from internal list // Also prints debug message with level INFO virtual void handle_disconnect(TCPSocket &socket); private: int listensocket_; // Listening socket file descriptor std::vector clients_; // Connected clients // Parts of do_events split up void do_accept(); // Accept any new connections void do_recv(); // Receive any new data and disconnect on failed reads }; #endif