GrpcPrint/PrintS/DataManage/ClientInfo.h

89 lines
2.0 KiB
C++

#pragma once
#include <mutex>
#include <string>
#include <thread>
#include <list>
#include "RWData.h"
#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;
}
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 {
WriteData* wd = m_msgList.front();
if (!wd) return false;
msg = *wd;
delete wd;
m_msgList.pop_front();
return true;
}
}
void PushMsg(WriteData* msg) {
std::lock_guard<std::mutex> lock(m_msgLock);
m_msgList.push_back(msg);
}
public:
std::string m_clientAddr; //客户端地址
bool m_readQuitFlag; //读线程退出标致
bool m_writeQuitFlag; //写线程退出标致
ServerContext* m_context; //上下文
private:
std::list<WriteData*> m_msgList; //信息缓存区
std::mutex m_msgLock; //信息锁
};
class ClientWrapper {
public:
static ClientWrapper* Instance() {
static ClientWrapper* clientWrapper = new ClientWrapper();
return clientWrapper;
}
void AddClient(ClientInfo* clientInfo); //添加客户端
void OfflineCheck(); //下线检测
void Clear(); //清空客户端
void PushAllClient(WriteData* wd);
bool IsExist(ClientInfo* ci);
private:
ClientWrapper() {}
~ClientWrapper() {}
ClientWrapper(const ClientWrapper& clientWrapper) = delete;
ClientWrapper& operator= (const ClientWrapper& clientWrapper) = delete;
private:
std::mutex m_mux;
std::list<ClientInfo*> m_clientList;
};