Implemented/fixed Windows/MSVC support for sockets.

This commit is contained in:
2024-08-19 18:35:55 +02:00
parent 35e7131780
commit df260808b9
5 changed files with 217 additions and 51 deletions

View File

@@ -6,6 +6,7 @@
#include <array>
#include <variant>
#include "../detect.hpp"
#include "../async/coroutine.hpp"
#include "../container/optional.hpp"
#include "../io/stream.hpp"
@@ -17,6 +18,16 @@ namespace mijin
// public types
//
#if MIJIN_TARGET_OS == MIJIN_OS_WINDOWS
using socket_handle_t = std::uintptr_t;
inline constexpr socket_handle_t INVALID_SOCKET_HANDLE = static_cast<socket_handle_t>(-1);
#else
using socket_handle_t = int;
inline constexpr socket_handle_t INVALID_SOCKET_HANDLE = -1;
#endif
struct IPv4Address
{
std::array<std::uint8_t, 4> octets;
@@ -86,7 +97,7 @@ public:
class TCPStream : public Stream
{
private:
int handle_ = -1;
socket_handle_t handle_ = INVALID_SOCKET_HANDLE;
bool async_ = false;
public:
StreamError readRaw(std::span<std::uint8_t> buffer, const ReadOptions& options, std::size_t* outBytesRead) override;
@@ -101,7 +112,7 @@ public:
StreamError open(ip_address_t address, std::uint16_t port) noexcept;
void close() noexcept;
[[nodiscard]] bool isOpen() const noexcept { return handle_ >= 0; }
[[nodiscard]] bool isOpen() const noexcept { return handle_ != INVALID_SOCKET_HANDLE; }
private:
void setAsync(bool async);
@@ -133,9 +144,17 @@ public:
class TCPServerSocket : public ServerSocket
{
private:
int handle_ = -1;
socket_handle_t handle_ = INVALID_SOCKET_HANDLE;
public:
StreamError setup(const char* address, std::uint16_t port) noexcept;
StreamError setup(ip_address_t address, std::uint16_t port) noexcept;
StreamError setup(std::string_view addressText, std::uint16_t port) noexcept
{
if (Optional<ip_address_t> address = ipAddressFromString(addressText); !address.empty())
{
return setup(*address, port);
}
return StreamError::UNKNOWN_ERROR;
}
void close() noexcept override;
[[nodiscard]] bool isListening() const noexcept { return handle_ >= 0; }