TCP服务器

class ResponseHandler {
public:
    ResponseHandler(int client_fd) : client_fd(client_fd) {}

    void sendResponse(const nlohmann::json& response) {
        std::string response_str = response.dump();
        send(client_fd, response_str.c_str(), response_str.size(), 0);
    }

private:
    int client_fd;
};

class UserAuth {
public:
    static bool login(const std::string& username, 
    const std::string& password, std::string& session_id,
    ResponseHandler* response_handler) {
        std::string salt = getSaltFromDatabase(username);
        std::string hashed_password = hashPassword(password, salt);

        if (hashed_password == getPasswordHashFromDatabase(username)) {
            session_id = generateSessionID();
            sessions[session_id] = "active"; // 记录用户状态为 active
            session_response_map[session_id] = response_handler; // 记录 Session ID 与 ResponseHandler 的映射
            return true;
        }
        return false;
    }

    static std::string getUserStatus(const std::string& session_id) {
        auto it = sessions.find(session_id);
        if (it != sessions.end()) {
            return it->second; // 返回用户状态
        }
        return "invalid"; // 如果找不到 Session ID,则返回无效状态
    }

    static void logout(const std::string& session_id) {
        sessions.erase(session_id); // 注销用户会话
        session_response_map.erase(session_id); // 移除 Session ID 与 ResponseHandler 的映射
    }

    static ResponseHandler* getResponseHandler(const std::string& session_id) {
        auto it = session_response_map.find(session_id);
        if (it != session_response_map.end()) {
            return it->second; // 返回对应的 ResponseHandler
        }
        return nullptr; // 如果找不到,返回 nullptr
    }

private:
    static std::unordered_map<std::string, std::string> sessions;
    static std::unordered_map<std::string, ResponseHandler*> session_response_map; // 存储 Session ID 与 ResponseHandler 的映射

    static std::string getSaltFromDatabase(const std::string& username) {
        return "random_salt"; // 示例返回
    }

    static std::string getPasswordHashFromDatabase(const std::string& username) {
        return "hashed_password"; // 示例返回
    }

    static std::string hashPassword(const std::string& password, const std::string& salt) {
        std::string salted_password = password + salt;
        unsigned char digest[MD5_DIGEST_LENGTH];
        MD5((unsigned char*)salted_password.c_str(), salted_password.size(), digest);

        char md5_string[33];
        for (int i = 0; i < 16; ++i) {
            sprintf(&md5_string[i * 2], "%02x", (unsigned int)digest[i]);
        }
        return std::string(md5_string);
    }

    static std::string generateSessionID() {
        auto now = std::chrono::system_clock::now().time_since_epoch().count();
        std::string session_id = std::to_string(now) + "_" + std::to_string(rand());
        return session_id;
    }
};

// 初始化静态成员
std::unordered_map<std::string, std::string> UserAuth::sessions;
std::unordered_map<std::string, ResponseHandler*> UserAuth::session_response_map;
class TCPServer {
public:
    TCPServer(int port) : port(port), running(false) {}

    void start() {
        running = true;
        std::thread(&TCPServer::run, this).detach();
    }

    void stop() {
        running = false;
        close(server_fd);
    }

private:
    void run() {
        server_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (server_fd < 0) {
            std::cerr << "Socket creation failed" << std::endl;
            return;
        }

        struct sockaddr_in address;
        address.sin_family = AF_INET;
        address.sin_addr.s_addr = INADDR_ANY;
        address.sin_port = htons(port);

        if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
            std::cerr << "Bind failed" << std::endl;
            return;
        }

        listen(server_fd, 3);

        int epoll_fd = epoll_create1(0);
        struct epoll_event event;
        event.events = EPOLLIN;
        event.data.fd = server_fd;
        epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_fd, &event);

        while (running) {
            struct epoll_event events[10];
            int nfds = epoll_wait(epoll_fd, events, 10, -1);

            for (int i = 0; i < nfds; ++i) {
                if (events[i].data.fd == server_fd) {
                    // 处理新的连接
                    int client_fd = accept(server_fd, nullptr, nullptr);
                    if (client_fd >= 0) {
                        event.events = EPOLLIN;
                        event.data.fd = client_fd;
                        epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &event);
                    }
                } else {
                    // 处理客户端请求
                    handleRequest(events[i].data.fd);
                }
            }
        }

        close(epoll_fd);
    }

    void handleRequest(int client_fd) {
        char buffer[1024] = {0};
        read(client_fd, buffer, sizeof(buffer));
        std::cout << "Received request: " << buffer << std::endl;

        // 解析 JSON 请求
        nlohmann::json request = nlohmann::json::parse(buffer);
        std::string action = request["action"];

        if (action == "login") {
            std::string username = request["username"];
            std::string password = request["password"];
            std::string session_id;

            // 创建 ResponseHandler 实例
            ResponseHandler response_handler(client_fd);

            if (UserAuth::login(username, password, session_id, &response_handler)) {
                nlohmann::json response = {
                    {"status", "success"},
                    {"session_id", session_id}
                };
                response_handler.sendResponse(response);
            } else {
                nlohmann::json response = {
                    {"status", "error"},
                    {"message", "Invalid username or password"}
                };
                response_handler.sendResponse(response);
            }
        } else if (action == "get_video_key") {
            std::string session_id = request["session_id"];
            std::string user_status = UserAuth::getUserStatus(session_id);

            if (user_status == "active") {
                // 获取对应的 ResponseHandler
                ResponseHandler* response_handler = UserAuth::getResponseHandler(session_id);
                if (response_handler) {
                    notifyClientForVideoKey(session_id, response_handler);
                }
            } else {
                nlohmann::json response = {
                    {"status", "error"},
                    {"message", "Session is invalid"}
                };
                ResponseHandler response_handler(client_fd);
                response_handler.sendResponse(response);
            }
        }
    }

    void notifyClientForVideoKey(const std::string& session_id, ResponseHandler* response_handler) {
        // 获取视频密钥的逻辑
        std::string video_key = "your_video_key"; // 示例返回

        nlohmann::json response = {
            {"status", "success"},
            {"video_key", video_key}
        };
        response_handler->sendResponse(response);
    }

    int server_fd;
    int port;
    bool running;
};