-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathSocket.h
80 lines (63 loc) · 1.98 KB
/
Socket.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef THORSANVIL_SOCKET_SOCKET_H
#define THORSANVIL_SOCKET_SOCKET_H
#include <string>
#include <vector>
#include <sstream>
namespace ThorsAnvil
{
namespace Socket
{
// An RAII base class for handling sockets.
// Socket is movable but not copyable.
class BaseSocket
{
int socketId;
protected:
static constexpr int invalidSocketId = -1;
// Designed to be a base class not used used directly.
BaseSocket(int socketId);
int getSocketId() const {return socketId;}
public:
virtual ~BaseSocket();
// Moveable but not Copyable
BaseSocket(BaseSocket&& move) noexcept;
BaseSocket& operator=(BaseSocket&& move) noexcept;
void swap(BaseSocket& other) noexcept;
BaseSocket(BaseSocket const&) = delete;
BaseSocket& operator=(BaseSocket const&) = delete;
// User can manually call close
void close();
};
// A class that can read/write to a socket
class DataSocket: public BaseSocket
{
public:
DataSocket(int socketId)
: BaseSocket(socketId)
{}
template<typename F>
std::size_t getMessageData(char* buffer, std::size_t size, F scanForEnd = [](std::size_t){return false;});
void putMessageData(char const* buffer, std::size_t size);
void putMessageClose();
};
// A class the conects to a remote machine
// Allows read/write accesses to the remote machine
class ConnectSocket: public DataSocket
{
public:
ConnectSocket(std::string const& host, int port);
};
// A server socket that listens on a port for a connection
class ServerSocket: public BaseSocket
{
static constexpr int maxConnectionBacklog = 5;
public:
ServerSocket(int port);
// An accepts waits for a connection and returns a socket
// object that can be used by the client for communication
DataSocket accept();
};
}
}
#include "Socket.tpp"
#endif