Quarts/SharedIPC/ipc_controller.cpp
2025-05-27 10:11:22 +07:00

142 lines
4.3 KiB
C++

#include "ipc_interface.h"
#include <windows.h>
#include <thread>
#include <atomic>
#include <mutex>
#include <unordered_map>
#include "sharedipc.h"
#include <iostream>
class IPCControllerImpl : public IPCController {
public:
IPCControllerImpl() : hMapFile(nullptr), hEvent(nullptr), isRunning(false) {
// Инициализация shared memory и событий
hEvent = CreateEventA(nullptr, FALSE, FALSE, "Local\\IPCEvent");
if (hEvent == NULL) {
DWORD err = GetLastError();
std::cerr << "hEvent failed: " << err << std::endl;
// return;
}
hMapFile = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 1024, "Local\\IPCMemory");
if (hMapFile == NULL) {
DWORD err = GetLastError();
std::cerr << "hMapFile failed: " << err << std::endl;
// return;
}
}
~IPCControllerImpl() {
stopListening();
CloseHandle(hEvent);
CloseHandle(hMapFile);
}
void sendMessage(const std::string& msg) override {
// std::cout << "IPC_Controller::sendMessage: " << msg << std::endl << std::flush;
LPVOID pBuf = MapViewOfFile(hMapFile, FILE_MAP_WRITE, 0, 0, 1024);
if (pBuf) {
memcpy(pBuf, msg.c_str(), msg.size() + 1);
SetEvent(hEvent); // Уведомляем получателей
UnmapViewOfFile(pBuf);
} else {
std::cout << "IPC_Controller::sendMessage: pBuf is empty" << std::endl << std::flush;
DWORD err = GetLastError();
std::cerr << "pBuf failed: " << err << std::endl;
}
}
void setMessageCallback(std::function<void(const std::string&)> callback) override {
messageCallback = callback;
}
void startListening() override {
if (isRunning) return;
isRunning = true;
listenerThread = std::thread(&IPCControllerImpl::listenLoop, this);
}
void stopListening() override {
isRunning = false;
SetEvent(hEvent); // Прерываем ожидание
if (listenerThread.joinable()) listenerThread.join();
}
private:
void listenLoop() {
while (isRunning) {
WaitForSingleObject(hEvent, INFINITE); // Ожидаем уведомление
if (!isRunning) break;
LPVOID pBuf = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 1024);
if (pBuf && messageCallback) {
messageCallback(static_cast<const char*>(pBuf));
UnmapViewOfFile(pBuf);
}
}
}
HANDLE hMapFile;
HANDLE hEvent;
std::atomic<bool> isRunning;
std::thread listenerThread;
std::function<void(const std::string&)> messageCallback;
};
class IPCControllerFactoryImpl : public IPCControllerFactory {
public:
~IPCControllerFactoryImpl() {
std::lock_guard<std::mutex> lock(mutex_);
for (auto& pair : controllers_) {
delete pair.second;
}
}
IPCController* getController(const std::string& memoryKey) override {
std::lock_guard<std::mutex> lock(mutex_);
// Если контроллер уже существует
auto it = controllers_.find(memoryKey);
if (it != controllers_.end()) {
return it->second;
}
// Создаём новый контроллер
auto* controller = new IPCControllerImpl();
controllers_[memoryKey] = controller;
return controller;
}
IPCController* getExistController(const std::string& memoryKey) override {
std::lock_guard<std::mutex> lock(mutex_);
// Если контроллер уже существует
auto it = controllers_.find(memoryKey);
if (it != controllers_.end()) {
return it->second;
}
return 0;
}
void releaseController(const std::string& memoryKey) override {
std::lock_guard<std::mutex> lock(mutex_);
auto it = controllers_.find(memoryKey);
if (it != controllers_.end()) {
delete it->second;
controllers_.erase(it);
}
}
private:
std::unordered_map<std::string, IPCController*> controllers_;
std::mutex mutex_;
};
extern "C" __declspec(dllexport) IPCControllerFactory* createIPCControllerFactory() {
return new IPCControllerFactoryImpl();
}