Files
OnlineRpg/include/common/SocketWrapper.h
2025-10-26 20:44:58 +08:00

140 lines
2.7 KiB
C++

#pragma once
#include <string>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
typedef SOCKET SocketFd;
#define INVALID_SOCKET_FD INVALID_SOCKET
#define SOCKET_ERROR_CODE WSAGetLastError()
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
typedef int SocketFd;
#define INVALID_SOCKET_FD -1
#define SOCKET_ERROR_CODE errno
#define closesocket close
#endif
/**
* @brief Socket 封装类
*
* 技术点: 网络编程 (Network Programming) - 原生 Socket API 封装
* 跨平台支持: Windows (Winsock) 和 Linux (POSIX Sockets)
*/
class SocketWrapper {
private:
SocketFd m_socket;
bool m_isValid;
public:
/**
* @brief 构造函数
*/
SocketWrapper();
/**
* @brief 构造函数 (使用现有socket)
*/
explicit SocketWrapper(SocketFd socket);
/**
* @brief 析构函数
*/
~SocketWrapper();
// 禁止拷贝
SocketWrapper(const SocketWrapper&) = delete;
SocketWrapper& operator=(const SocketWrapper&) = delete;
/**
* @brief 初始化 Winsock (仅 Windows)
*/
static bool initializeWinsock();
/**
* @brief 清理 Winsock (仅 Windows)
*/
static void cleanupWinsock();
/**
* @brief 创建 Socket
*/
bool create();
/**
* @brief 绑定地址和端口
*/
bool bind(const std::string& address, int port);
/**
* @brief 监听连接
*/
bool listen(int backlog = 10);
/**
* @brief 接受客户端连接
*/
SocketFd accept(std::string& clientAddress, int& clientPort);
/**
* @brief 连接到服务器
*/
bool connect(const std::string& address, int port);
/**
* @brief 发送数据
*/
int send(const char* data, int length);
/**
* @brief 发送字符串
*/
int send(const std::string& message);
/**
* @brief 接收数据
*/
int recv(char* buffer, int length);
/**
* @brief 接收一行数据 (以 \n 结尾)
*/
std::string recvLine();
/**
* @brief 设置为非阻塞模式
*/
bool setNonBlocking(bool nonBlocking);
/**
* @brief 设置 Socket 选项
*/
bool setReuseAddr(bool reuse);
/**
* @brief 关闭 Socket
*/
void close();
/**
* @brief 检查 Socket 是否有效
*/
bool isValid() const { return m_isValid; }
/**
* @brief 获取原始 Socket 描述符
*/
SocketFd getSocket() const { return m_socket; }
/**
* @brief 获取最后的错误信息
*/
static std::string getLastError();
};