-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServer.mpp
More file actions
63 lines (55 loc) · 1.7 KB
/
Server.mpp
File metadata and controls
63 lines (55 loc) · 1.7 KB
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
module;
#include <CppUtils/System/OS.hpp>
#if defined(OS_WINDOWS)
# include <winsock2.h>
# pragma comment(lib, "ws2_32.lib")
#elif defined(OS_LINUX) or defined(OS_MACOS)
# include <sys/socket.h>
# include <cerrno>
#endif
export module CppUtils.Network.Server;
import std;
export import CppUtils.Network.Socket;
export namespace CppUtils::Network
{
class Server final: public Socket
{
public:
explicit inline Server(
Socket::Domain domain = Socket::Domain::IPV4,
Socket::Type type = Socket::Type::TCP):
Socket{domain, type}
{
auto _ = setIPv6Only(false);
}
[[nodiscard]] inline auto bind(std::uint16_t port) const -> std::expected<void, std::error_code>
{
auto address = makeAddress("", port);
if (auto result = expectSocket(::bind(nativeHandle(), reinterpret_cast<sockaddr*>(std::addressof(address.storage)), address.length)); not result)
return std::unexpected{result.error()};
return {};
}
[[nodiscard]] inline auto listen(std::size_t waitingQueue = 10) -> std::expected<void, std::error_code>
{
if (auto result = expectSocket(::listen(nativeHandle(), static_cast<int>(waitingQueue))); not result)
return std::unexpected{result.error()};
return {};
}
[[nodiscard]] inline auto accept() -> std::expected<Socket, std::error_code>
{
auto clientSocket = ::accept(nativeHandle(), nullptr, nullptr);
#if defined(OS_WINDOWS)
if (clientSocket == INVALID_SOCKET)
#else
if (clientSocket < 0)
#endif
{
const auto error = lastErrorCode();
if (isWouldBlock())
return std::unexpected{std::make_error_code(std::errc::resource_unavailable_try_again)};
return std::unexpected{error};
}
return Socket{clientSocket, getDomain(), getType()};
}
};
}