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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include "ProtocolDef.h"
#include <string.h>
#include <boost/format.hpp>
#include "Exception.h"
namespace netcode {
ProtocolDef* ProtocolDef::instance_ptr = 0;
ProtocolDef* ProtocolDef::instance()
{
if (!instance_ptr)
{
instance_ptr = new ProtocolDef();
}
return instance_ptr;
}
ProtocolDef::ProtocolDef()
{
memset(msg, '\0', sizeof(MsgType)*256);
}
void ProtocolDef::AddType(const unsigned char id, const int MsgLength)
{
msg[id].Length = MsgLength;
}
bool ProtocolDef::HasFixedLength(const unsigned char id) const
{
if (msg[id].Length > 0)
return true;
else if (msg[id].Length < 0)
return false;
else
{
throw network_error(str( boost::format("Unbound Message Type: %1%") %(unsigned int)id ));
}
}
bool ProtocolDef::IsAllowed(const unsigned char id) const
{
if (msg[id].Length != 0)
return true;
else
return false;
}
int ProtocolDef::GetLength(const unsigned char id) const
{
return msg[id].Length;
}
unsigned ProtocolDef::IsComplete(const unsigned char* const buf, const unsigned bufLength) const
{
if (bufLength == 0)
{
return 0;
}
else
{
if (HasFixedLength(buf[0]))
{
if (bufLength >= (unsigned int)GetLength(buf[0]))
return GetLength(buf[0]);
else
return 0;
}
else
{
int var = GetLength(buf[0]);
if (var == -1)
{
if (bufLength < 2)
return 0;
var = buf[1];
}
else if (var == -2)
{
if (bufLength <= 2)
return 0;
var = *((unsigned short*)(buf + 1));
}
if (bufLength >= (unsigned int)var)
return var;
else
return 0;
}
}
}
} // namespace netcode
|