在后端开发中用到一些libuv库,如下是对libuv库的一些封装,便于以后扩展使用。
uvdefine.h
#ifndef __UVDEFINE__H_
#define __UVDEFINE__H_
#include "uv.h"
#define UV_DEFAULT_BUF_SIZE 10240 //default 10KB buffer size
struct tagUvBuf {
char* pBuf;
ssize_t iLen;
ssize_t iUse;
ssize_t iTotal;
};
#endif
如下是libuv的公共基类封装
#ifndef __CUVBASE__H_
#define __CUVBASE__H_
#include "uvdefine.h"
#include "CLogmanager.h"
class CUvBase : {
public:
CUvBase();
virtual ~CUvBase();
public:
void SetUvLoop(uv_loop_t* const pUvLoop) { mpUvLoop = pUvLoop; }
virtual uv_loop_t* GetUvLoop() { return mpUvLoop; }
int Init(ssize_t iBufSize = UV_DEFAULT_BUF_SIZE);
int StartBaseTimer(uint64_t iTimeout, uint64_t iRepeat);
int StopBaseTimer();
protected:
static void UvBufAlloc(uv_handle_t* pStream, size_t iSize, uv_buf_t* pBuf);
static void BaseTimerOut(uv_timer_t* pHandler);
protected:
virtual int OnInit() = 0;
virtual void OnBaseTimer();
protected:
void ResetUvBuf();
protected:
uv_loop_t* mpUvLoop;
uv_timer_t mstUvTimer;
tagUvBuf mstUvBuf;
};
#endif
#include "UvBase.h"
CUvBase::CUvBase(){
mpUvLoop = nullptr;
memset(&mstUvBuf, 0, sizeof(mstUvBuf));
}
CUvBase::~CUvBase(){
if (nullptr != mstUvBuf.pBuf) {
DOFREE(mstUvBuf.pBuf);
}
}
void CUvBase::ResetUvBuf() {
mstUvBuf.iUse = 0;
mstUvBuf.iTotal = 0;
}
void CUvBase::UvBufAlloc(uv_handle_t* pStream, size_t iSize, uv_buf_t* pBuf) {
CUvBase* pUvBase = (CUvBase*)uv_handle_get_data((uv_handle_t*)pStream);
if (nullptr != pUvBase && nullptr != pUvBase->mstUvBuf.pBuf)
{
*pBuf = uv_buf_init(pUvBase->mstUvBuf.pBuf + pUvBase->mstUvBuf.iUse, (unsigned int)(pUvBase->mstUvBuf.iLen - pUvBase->mstUvBuf.iUse));
}
else
{
LOG_ERR("RtpStreamAlloc Error");
}
}
int CUvBase::Init(ssize_t iBufSize) {
ASSERT_RET_VALUE(nullptr != mpUvLoop, 1);
ASSERT_RET_VALUE(iBufSize > 0, 1);
mstUvBuf.pBuf = (char*)do_malloc(iBufSize);
mstUvBuf.iLen = iBufSize;
return OnInit();
}
void CUvBase::BaseTimerOut(uv_timer_t* pHandler) {
CUvBase* pUvBase = (CUvBase*)uv_handle_get_data((uv_handle_t*)pHandler);
if (nullptr != pUvBase){
pUvBase->OnBaseTimer();
}
}
void CUvBase::OnBaseTimer() {
}
int CUvBase::StopBaseTimer() {
uv_close((uv_handle_t*)&mstUvTimer, nullptr);
return 0;
}
int CUvBase::StartBaseTimer(uint64_t iTimeout, uint64_t iRepeat) {
ASSERT_RET_VALUE(nullptr != mpUvLoop, 1);
return uv_timer_start(&mstUvTimer, CUvBase::BaseTimerOut, iTimeout, iRepeat);
}