]> git.tdb.fi Git - libs/net.git/blob - source/socket.h
c2c17f07dc2d2f42611bbb818bbf45c920c6c04f
[libs/net.git] / source / socket.h
1 #ifndef MSP_NET_SOCKET_H_
2 #define MSP_NET_SOCKET_H_
3
4 #include <msp/io/eventobject.h>
5 #include <msp/io/handle.h>
6 #include "constants.h"
7 #include "sockaddr.h"
8 #include "types.h"
9
10 namespace Msp {
11 namespace Net {
12
13 class bad_socket_state: public std::logic_error
14 {
15 public:
16         bad_socket_state(const std::string &w): std::logic_error(w) { }
17         virtual ~bad_socket_state() throw() { }
18 };
19
20
21 class Socket: public IO::EventObject
22 {
23 protected:
24         SocketHandle handle;
25         IO::Handle event;
26         bool connected;
27         SockAddr *local_addr;
28         SockAddr *peer_addr;
29
30         Socket(SocketHandle, const SockAddr &);
31         Socket(Family, int, int);
32 public:
33         ~Socket();
34
35         void set_block(bool);
36         const IO::Handle &get_event_handle();
37
38         bool is_connected() const { return connected; }
39         
40         /** Associates the socket with a local address.  There must be no existing
41         users of the address. */
42         void bind(const SockAddr &);
43
44         /** Connects to a remote address.  Exact semantics depend on the socket
45         type. */
46         virtual int connect(const SockAddr &) = 0;
47
48         /// Closes the socket.  Most operations will throw an exception after this.
49         void close();
50
51         void set_timeout(const Time::TimeDelta &);
52         const SockAddr &get_local_address() const;
53         const SockAddr &get_peer_address() const;
54 protected:
55         void check_state(bool) const;
56         int set_option(int, int, const void *, socklen_t);
57         int get_option(int, int, void *, socklen_t *) const;
58         unsigned do_write(const char *, unsigned);
59         unsigned do_read(char *, unsigned);
60 };
61
62 } // namespace Net
63 } // namespace Msp
64
65 #endif