FiberIO
Fiber-based C++ network library
socket.hpp
Go to the documentation of this file.
1 #ifndef _FIBERIO_SOCKET_H_
2 #define _FIBERIO_SOCKET_H_
3 
4 #include <memory>
5 #include <string>
6 
7 namespace fiberio {
8 
9 class socket_impl;
10 
12 class socket
13 {
14 public:
15  static constexpr std::size_t DEFAULT_BUF_SIZE = 256 * 1024;
16 
18  socket();
19 
21  socket(const socket&);
22 
24  socket(socket&&);
25 
27  socket(std::shared_ptr<socket_impl>&& impl);
28 
30  ~socket();
31 
33  socket& operator=(const socket& other);
34 
36  socket& operator=(socket&& other);
37 
39  void connect(const std::string& host, uint16_t port);
40 
47  std::size_t read(char* buf, std::size_t size);
48 
50  void read_exactly(char* buf, std::size_t size);
51 
60  std::string read_string(std::size_t count = DEFAULT_BUF_SIZE,
61  bool shrink_to_fit = true);
62 
64  std::string read_string_exactly(std::size_t count);
65 
67  void write(const char* data, std::size_t len);
68 
70  void write(const std::string& data);
71 
76  void close();
77 
83  bool is_open();
84 
85 private:
86  std::shared_ptr<socket_impl> impl_;
87 };
88 
89 
90 }
91 
92 #endif
void close()
Closes the socket if it&#39;s not already closed.
~socket()
Destructor. Closes the socket if still open.
socket()
Creates a non-connected socket.
Client socket for communicating over a network and opening connections.
Definition: socket.hpp:12
void connect(const std::string &host, uint16_t port)
Connects to host:port and throws an exception on failure.
std::size_t read(char *buf, std::size_t size)
Reads up to size bytes into buf.
void write(const char *data, std::size_t len)
Writes data from the buffer and returns once the buffer can be freed.
static constexpr std::size_t DEFAULT_BUF_SIZE
Definition: socket.hpp:15
socket & operator=(const socket &other)
Copy assignment.
std::string read_string_exactly(std::size_t count)
The same as read_string() but reads exactly count bytes (or fails)
std::string read_string(std::size_t count=DEFAULT_BUF_SIZE, bool shrink_to_fit=true)
Reads up to count bytes and returns it as an std::string.
void read_exactly(char *buf, std::size_t size)
The same as read() but always fills the buffer completely (or fails)
bool is_open()
Check if the connection is open.