00001 #ifndef UTILMM_SOCKET_HH 00002 #define UTILMM_SOCKET_HH 00003 00004 #include <boost/noncopyable.hpp> 00005 #include <string> 00006 #include <vector> 00007 00008 namespace utilmm 00009 { 00014 class base_socket : boost::noncopyable 00015 { 00016 public: 00017 enum Domain { Unix, Inet }; 00018 enum Type { Stream, Datagram }; 00019 enum Wait { WaitRead = 1, WaitWrite = 2, WaitException = 4}; 00020 00021 private: 00022 static int to_unix(Domain d); 00023 static int to_unix(Type t); 00024 00025 struct bad_address : public std::exception { }; 00026 00027 int m_fd; 00028 Domain m_domain; 00029 Type m_type; 00030 00031 int wait(int what, timeval* tv) const; 00032 00033 protected: 00034 std::vector<uint8_t> to_sockaddr(std::string const& to) const; 00035 00036 public: 00037 base_socket(int fd); 00038 base_socket(Domain domain, Type type); 00039 00041 ~base_socket(); 00042 00044 int fd() const; 00045 00051 bool try_wait(int what) const; 00052 00057 void wait(int what) const; 00058 00060 void flush() const; 00061 }; 00062 00067 class socket : public base_socket 00068 { 00069 friend class server_socket; 00070 00071 public: 00073 socket(int fd); 00074 00080 socket(Domain domain, Type type, std::string const& connect_to); 00081 00086 void connect(std::string const& to); 00087 00093 int read(void* buf, size_t size) const; 00094 00100 int write(void const* buf, size_t size) const; 00101 }; 00102 00107 class server_socket : public base_socket 00108 { 00109 public: 00110 server_socket(Domain domain, Type type, std::string const& bind_to, int backlog = 256); 00111 00112 void bind(std::string const& to); 00113 00118 socket* accept() const; 00119 00123 bool try_wait() const; 00124 00126 void wait() const; 00127 }; 00128 } 00129 00130 #endif 00131