#include "huslib.h" #include "huslibex.h" #include "SohHandler.h" HSohHandler::HSohHandler() { m_pRecvBuffer = new HStreamBuffer(HH_SOH_MAX_COMMAND_PACKET_SIZE); m_nBodySize = 0; m_pSendBuffer = new HStreamBuffer(HH_SOH_MAX_COMMAND_PACKET_SIZE); } HSohHandler::~HSohHandler() { delete m_pRecvBuffer; delete m_pSendBuffer; } int HSohHandler::SendBufferedPacket() { int nSentSize = SendToTransport(m_pSendBuffer->Head(), m_pSendBuffer->StoredSize()); if (nSentSize <= 0) return nSentSize; m_pSendBuffer->Pop(nSentSize); return nSentSize; } int HSohHandler::SendPacket(const char * pData, size_t nSize) { if (m_pSendBuffer->StoredSize() == 0) { int nSentSize = SendToTransport(pData, nSize); if (nSentSize < 0) return -1; if (nSentSize != nSize) m_pSendBuffer->Store(pData + nSentSize, nSize - nSentSize); return nSentSize; } m_pSendBuffer->Store(pData, nSize); return SendBufferedPacket(); } void HSohHandler::OnReceivedStatusFromTransport(int nStatus) { if (nStatus == HTransport::T_BEGIN_TRANSPORT) { OnInitialize(true); } else if (nStatus == HTransport::T_FAILED_BEGIN) { OnInitialize(false); } else if (nStatus == HTransport::T_END_TRANSPORT) { OnTerminate(); } } int HSohHandler::OnReceivedFromTransport(const char * pData, int nSize) { if (m_pRecvBuffer->Store(pData, nSize) == false) { HLOGF(HLOG_ERROR, "[ERROR], SohHdler, Failed to insert data, buffer = %d, stored = %d, recv size = %d\n", m_pRecvBuffer->Size(), m_pRecvBuffer->StoredSize(), nSize); return -1; // close connection } for (;;) { if (m_nBodySize > 0) { if (m_nBodySize > m_pRecvBuffer->StoredSize()) return 0; // receive remain packet } else { if (m_pRecvBuffer->StoredSize() < 4) return 0; // receive remain packet // get body size m_nBodySize = ntohs(*((u_short *)(m_pRecvBuffer->Head() + 2))); m_pRecvBuffer->Pop(4); // pop header // /*static int i = 0; if (i++ == 0) m_nBodySize = 69; //TestCode else m_nBodySize = 197; //TestCode*/ HLOGF(HLOG_ERROR, "[TRACE], SohHdler, m_nBodySize = %d\n", m_nBodySize); if (m_nBodySize > m_pRecvBuffer->StoredSize()) return 0; // receive remain packet } m_pRecvBuffer->Head()[m_nBodySize] = '\0'; if (OnReceivedBody(m_pRecvBuffer->Head(), m_nBodySize) < 0) return -1; // close connection m_pRecvBuffer->Pop(m_nBodySize); m_nBodySize = 0; } return -1; // close connection } int HSohHandler::OnSendRetryToTransport() { return SendBufferedPacket(); }