-
Notifications
You must be signed in to change notification settings - Fork 0
/
t_proto.cpp
54 lines (47 loc) · 1.47 KB
/
t_proto.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "t_proto.hpp"
#include <arpa/inet.h>
#include <string.h>
namespace T_TCP
{
// proto format: | 4 type head | payload |
BusiCodec::BusiCodec(int iType) :m_iCodeType(iType)
{
}
BusiCodec::~BusiCodec()
{
}
enum CODERET BusiCodec::DeCode(const char* pDstBuf, int iSrcLen, char* pSrcPayLoad, int *piPayLoadLen)
{
if (iSrcLen < sizeof(int))
{
*piPayLoadLen = 0;
return RET_RECV_NOT_COMPLETE;
}
int iHeadBufData = ::ntohl( *((int*)pDstBuf) );
if (iSrcLen >= iHeadBufData + sizeof(int))
{
::memcpy(pSrcPayLoad, pDstBuf + sizeof(int), iHeadBufData);
*piPayLoadLen = iHeadBufData + sizeof(int);
return RET_RECV_OK;
}
return RET_RECV_NOT_COMPLETE;
}
enum CODERET BusiCodec::EnCode(const char* pSrcBuf, int iSrcLen, char *pDstMsg, int* piDstMsgLen)
{
if (pSrcBuf == NULL || pDstMsg == NULL || piDstMsgLen == NULL)
{
return RET_RECV_ERR;
}
char *pPreCodeAddr = pDstMsg + (*piDstMsgLen);
char buf[1024];
::memset(buf, 0, sizeof(buf));
//set head content;
*((int*)buf) = ::htonl(iSrcLen);
//set body content
memcpy(buf + sizeof(int), pSrcBuf, iSrcLen);
//set conn send buf content.
memcpy(pPreCodeAddr, buf, iSrcLen + sizeof(int));
(*piDstMsgLen) += iSrcLen + sizeof(int);
return RET_RECV_OK;
}
}