PlayerSession::PlayerSession() :
m_Buffer((uint8*)malloc(1)),
m_BufferLength(0)
{
}
PlayerSession::~PlayerSession()
{
free(m_Buffer);
m_Buffer = nullptr;
}
void PlayerSession::onRecvBuffer(char* buffer, uint32 length)
{
m_BufferLocker.lock();
if (2147483647 - m_BufferLength < length)
throw("Not Enough Length Exception");
realloc(m_Buffer, m_BufferLength + length);
memcpy(m_Buffer[m_BufferLength], buffer, length);
m_BufferLength += length;
m_BufferLocker.unlock();
}
WorldPacket* PlayerSession::tryGetNextPacket()
{
WorldPacket* packet = nullptr;
m_BufferLocker.lock();
//PacketHeaderSize
if (m_BufferLength > 4/*Size Of Uint32*/)
{
uint32 packetSize = *(uint32*)m_Buffer;
if (m_BufferLength >= packetSize)
{
uint16 headerSize = *(((uint16*)m_Buffer)[2]);
uint32 bodySize = packetSize - 6;/* sizeof(uint32) + sizeof(uint16) --> lengthSize + headerSize */
if (WorldPacket* _packet = new(std::nothrow) WorldPacket(bodySize, headerSize))
{
if (char* packetBuffer = new(std::nothrow) char[bodySize]())
{
memcpy(packetBuffer/*dst*/, ((char*) m_Buffer )[6] /*src*/, bodySize/*length*/);
_packet->setData(packetBuffer);
packet = _packet;
//Algin Buffers
m_BufferLength -= packetSize;
memcpy(m_Buffer, m_Buffer[packetSize], m_BufferLength);
realloc(m_Buffer, m_BufferLength);
}
else
{
delete _packet;
_packet = nullptr;
}
}
}
}
m_BufferLocker.unlock();
if (!packet)
sLog->OutException("Malloc Exception");
return packet;
}