GrpcPrint/PrintS/DataManage/ClientInfo.h

97 lines
2.2 KiB
C
Raw Normal View History

2024-03-19 17:45:12 +08:00
#pragma once
#include <mutex>
#include <string>
#include <thread>
#include <list>
2024-04-10 16:15:33 +08:00
#include "RWData.h"
2024-03-19 17:45:12 +08:00
#include "../protobuf/stream.grpc.pb.h"
using grpc::ServerContext;
class ClientInfo {
public:
ClientInfo()
: m_clientAddr("0.0.0.0:0")
, m_readQuitFlag(false)
, m_writeQuitFlag(false)
, m_context(nullptr) {
}
~ClientInfo() {
m_readQuitFlag = true;
m_writeQuitFlag = true;
std::lock_guard<std::mutex> lock(m_msgLock);
auto lst = m_msgList.begin();
while (lst != m_msgList.end()) {
delete (*lst);
2024-04-24 18:12:41 +08:00
++lst;
}
m_msgList.clear();
2024-03-19 17:45:12 +08:00
}
bool IsConnect() {
return m_context && !m_context->IsCancelled();
}
bool GetPushMsg(WriteData& msg) {
std::lock_guard<std::mutex> lock(m_msgLock);
if (m_msgList.empty()) {
return false;
}
else {
2024-04-08 13:43:56 +08:00
WriteData* wd = m_msgList.front();
if (!wd) return false;
msg = *wd;
delete wd;
2024-03-19 17:45:12 +08:00
m_msgList.pop_front();
return true;
}
}
2024-04-10 16:15:33 +08:00
void PushMsg(WriteData* msg) {
2024-03-19 17:45:12 +08:00
std::lock_guard<std::mutex> lock(m_msgLock);
m_msgList.push_back(msg);
}
public:
2024-04-08 13:43:56 +08:00
std::string m_clientAddr; //客户端地址
bool m_readQuitFlag; //读线程退出标致
bool m_writeQuitFlag; //写线程退出标致
ServerContext* m_context; //上下文
2024-03-19 17:45:12 +08:00
private:
std::list<WriteData*> m_msgList; //信息缓存区
std::mutex m_msgLock; //信息锁
2024-04-10 16:15:33 +08:00
};
class ClientWrapper {
public:
static ClientWrapper* Instance() {
static ClientWrapper* clientWrapper = new ClientWrapper();
return clientWrapper;
}
void AddClient(ClientInfo* clientInfo); //添加客户端
void OfflineCheck(); //下线检测
void Clear(); //清空客户端
void PushAllClient(const WriteData& wd);
2024-04-10 16:15:33 +08:00
2024-04-12 15:51:41 +08:00
bool IsExist(ClientInfo* ci);
2024-04-10 16:15:33 +08:00
private:
ClientWrapper() {}
~ClientWrapper() {}
ClientWrapper(const ClientWrapper& clientWrapper) = delete;
ClientWrapper& operator= (const ClientWrapper& clientWrapper) = delete;
private:
std::mutex m_mux;
std::list<ClientInfo*> m_clientList;
2024-03-19 17:45:12 +08:00
};