SimpleSocket  0.1
Some wrappers that make using sockets easier in C++
All Classes Files Functions Pages
sclasses.hh
1 #pragma once
2 #include "swrappers.hh"
3 #include <boost/utility/string_ref.hpp>
4 
5 int SConnectWithTimeout(int sockfd, const ComboAddress& remote, double timeout);
6 
7 struct RAIISocket
8 {
9  RAIISocket(int fd) : d_fd(fd){}
10  RAIISocket(int domain, int type, int protocol=0)
11  {
12  d_fd = SSocket(domain, type, protocol);
13  }
14 
15  operator int()
16  {
17  return d_fd;
18  }
19 
20  void release()
21  {
22  d_fd=-1;
23  }
24  ~RAIISocket()
25  {
26  if(d_fd >= 0)
27  close(d_fd);
28  }
29  int d_fd;
30 };
31 
42 {
43 public:
45  explicit ReadBuffer(int fd, int bufsize=2048) : d_fd(fd), d_buffer(bufsize)
46  {}
47 
49  void setTimeout(double timeout)
50  {
51  d_timeout = timeout;
52  }
53 
55  inline bool getChar(char* c)
56  {
57  if(d_pos == d_endpos && !getMoreData())
58  return false;
59  *c=d_buffer[d_pos++];
60  return true;
61  }
62 
63 private:
64  bool getMoreData();
65  int d_fd;
66  std::vector<char> d_buffer;
67  unsigned int d_pos{0};
68  unsigned int d_endpos{0};
69  double d_timeout=-1;
70 };
71 
78 {
79 public:
81  explicit SocketCommunicator(int fd) : d_rb(fd), d_fd(fd)
82  {
83  SetNonBlocking(fd);
84  }
86  void connect(const ComboAddress& a)
87  {
88  SConnectWithTimeout(d_fd, a, d_timeout);
89  }
91  bool getLine(std::string& line);
92 
94  void writen(boost::string_ref message);
95 
97  void setTimeout(double timeout) { d_timeout = timeout; }
98 private:
99  ReadBuffer d_rb;
100  int d_fd;
101  double d_timeout{-1};
102 };
Definition: comboaddress.hh:78
Definition: sclasses.hh:7
void setTimeout(double timeout)
Set the timeout (in seconds)
Definition: sclasses.hh:97
int SSocket(int family, int type, int flags=0)
Create a socket. Error = exception.
Definition: swrappers.cc:14
Set of C++ friendly wrappers around socket-relevant calls.
Definition: sclasses.hh:41
void setTimeout(double timeout)
Set timeout in seconds.
Definition: sclasses.hh:49
void connect(const ComboAddress &a)
Connect to an address, with the default timeout (which may be infinite)
Definition: sclasses.hh:86
ReadBuffer(int fd, int bufsize=2048)
Instantiate on a non-blocking filedescriptor, with a given buffer size in bytes.
Definition: sclasses.hh:45
Definition: sclasses.hh:77
SocketCommunicator(int fd)
Instantiate on top of this file descriptor, which will be set to non-blocking.
Definition: sclasses.hh:81
bool getChar(char *c)
Gets you a character in c, or false in case of EOF.
Definition: sclasses.hh:55
void SetNonBlocking(int sockfd, bool to=true)
Set a socket to (non) blocking mode. Error = exception.
Definition: swrappers.cc:99