Files
CPP_Core/Core/socket/Socket.h
T
2026-07-24 10:54:45 +08:00

66 lines
1.8 KiB
C++

#pragma once
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include "../Base/JSON.h"
#include "../system/export.h"
#include "Core/spdlog/export.h"
namespace Psc::asio_socket {
#if _WIN32
using Socket_FD = unsigned long long;
#else
using Socket_FD = int;
#endif
extern BaseLogger* socket_logger;
struct Sockaddr_In {
std::string ip;
std::uint32_t port{};
Sockaddr_In() = default;
Sockaddr_In(std::string_view ip, std::uint32_t port) : ip(ip), port(port) {
}
[[nodiscard]] std::string to_string() const {
return ip + ":" + std::to_string(port);
}
bool operator<(const Sockaddr_In& other) const {
if (ip != other.ip)
return ip < other.ip;
return port < other.port;
}
bool operator==(const Sockaddr_In& other) const noexcept {
return ip == other.ip && port == other.port;
}
bool operator!=(const Sockaddr_In& other) const noexcept {
return !(*this == other);
}
};
struct Accept_Info {
Sockaddr_In sockaddr;
Socket_FD fd{};
[[nodiscard]] std::string to_string() const {
return "fd:" + std::to_string(fd) + ":[" + sockaddr.to_string() + "]";
}
};
class Socket_Base {
public:
virtual ~Socket_Base() = default;
std::optional<Sockaddr_In> address;
Socket_FD socket_fd = static_cast<Socket_FD>(-1);
virtual std::string to_string() {
return address ? address->to_string() : std::string{};
}
[[nodiscard]] JSON to_Json() const {
JSON ret = JSON::object();
ret.append({"fd", static_cast<std::uint64_t>(socket_fd)});
if (address) {
ret.append({"ip", address->ip});
ret.append({"port", address->port});
}
return ret;
}
virtual void close() {
socket_fd = static_cast<Socket_FD>(-1);
}
};
} // namespace Psc::asio_socket