openai-api/server/server.h

56 lines
1.3 KiB
C
Raw Normal View History

2025-03-04 15:17:10 +08:00
#ifndef SERVER_H
#define SERVER_H
#include <asio.hpp>
#include <mutex>
#include <unordered_map>
2025-04-14 21:01:36 +08:00
#include "communicate.hpp"
#include "jsondata.h"
#include "zapi.h"
2025-03-04 15:17:10 +08:00
struct ClientCache {
std::array<char, g_BuffSize> tmp_buf_{};
CMutBuffer buffer_{};
};
class Server
{
public:
Server(asio::io_context& io_context, short port);
2025-03-05 08:10:55 +08:00
~Server();
public:
2025-03-04 15:17:10 +08:00
void start();
void stop();
public:
void set_worker(std::shared_ptr<COpenAI> worker, std::shared_ptr<CJsonOper> json);
2025-03-05 09:20:03 +08:00
void set_token(long tokens);
2025-04-14 21:01:36 +08:00
2025-03-04 15:17:10 +08:00
private:
void do_accept();
2025-03-05 09:20:03 +08:00
void th_client(const std::shared_ptr<asio::ip::tcp::socket>& socket, const std::string& client_key);
2025-03-04 15:17:10 +08:00
2025-03-04 19:46:29 +08:00
std::string post_data(const std::string& data);
bool send_frame(const std::shared_ptr<asio::ip::tcp::socket>& socket, FrameData& data);
void print_exception(const std::exception& e);
2025-03-04 19:46:29 +08:00
2025-03-04 15:17:10 +08:00
private:
asio::io_context& io_context_;
asio::ip::tcp::acceptor acceptor_;
std::shared_ptr<COpenAI> worker_{};
std::shared_ptr<CJsonOper> json_{};
std::mutex ask_mutex_;
std::mutex cli_mutex_;
std::unordered_map<std::string, std::thread> clients_;
std::map<std::string, std::shared_ptr<ClientCache>> client_map_;
CMutBuffer buffer_{};
short port_;
2025-03-05 09:20:03 +08:00
long tokens_{};
long use_tokens_{};
2025-03-04 15:17:10 +08:00
};
2025-04-14 21:01:36 +08:00
#endif