Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <iostream>
- #include <sstream>
- #include <Windows.h>
- #include "networkmessage.h"
- NetworkMessage::NetworkMessage()
- {
- Reset();
- }
- NetworkMessage::~NetworkMessage()
- {
- }
- void NetworkMessage::Reset()
- {
- m_MsgSize = 0;
- m_ReadPos = 2;
- }
- bool NetworkMessage::ReadFromSocket(SOCKET socket)
- {
- // just read the size to avoid reading 2 messages at once
- m_MsgSize = recv(socket, (char*)m_MsgBuf, 2, 0);
- // for now we expect 2 bytes at once, it should not be splitted
- int datasize = m_MsgBuf[0] | m_MsgBuf[1] >> 8;
- if ((m_MsgSize != 2) || (datasize > NETWORKMESSAGE_MAXSIZE-2))
- {
- Reset();
- return false;
- }
- // read the real data
- m_MsgSize += recv(socket, (char*)m_MsgBuf+2, datasize, 0);
- // we got something unexpected/incomplete
- if ((m_MsgSize <= 2) || ((m_MsgBuf[0] | m_MsgBuf[1] >> 8) != m_MsgSize-2))
- {
- Reset();
- return false;
- }
- // ok, ...reading starts after the size
- m_ReadPos = 2;
- return true;
- }
- #ifndef __NETWORK_MESSAGE_H__
- #define __NETWORK_MESSAGE_H__
- #define NETWORKMESSAGE_MAXSIZE 16384
- class NetworkMessage
- {
- public:
- NetworkMessage();
- virtual ~NetworkMessage();
- // Resets the internal buffer to an empty message
- void Reset();
- // Socket functions
- bool ReadFromSocket(SOCKET socket);
- protected:
- int m_MsgSize;
- int m_ReadPos;
- unsigned char m_MsgBuf[NETWORKMESSAGE_MAXSIZE];
- };
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement