src/network/MessageOut.cpp

00001 #include "MessageOut.h"
00002 
00003 #include "NetPacket.h"
00004 
00005 MessageOut::MessageOut(const message_type m_type)
00006         :myData(NULL),
00007         myDataSize(0),
00008         pos(0),
00009         myPacket(NULL)
00010 {
00011         write2(m_type); //Writes the message type in the first two bytes of the message.
00012 }
00013 
00014 MessageOut::~MessageOut(){
00015         if(this->myPacket)
00016                 delete this->myPacket;
00017 }
00018 
00019 
00020 void MessageOut::write1(char value){
00021     expandData((this->pos) + 1);
00022     myData[this->pos] = value;
00023     this->pos += 1;
00024 }
00025 
00026 void MessageOut::write2(Uint16 value){
00027         expandData((this->pos) + 2);
00028         Uint16 tmp = SDL_SwapBE16(value);
00029         memcpy((this->myData)+(this->pos), &tmp, 2);
00030     this->pos += 2;
00031 }
00032 
00033 void MessageOut::write4(Uint32 value){
00034         expandData((this->pos) + 4);
00035         Uint32 tmp = SDL_SwapBE32(value);
00036         memcpy((this->myData)+(this->pos), &tmp, 4);
00037     this->pos += 4;
00038 }
00039 
00040 char* MessageOut::getData(){
00041         return this->myData;
00042 }
00043 
00044 Uint32 MessageOut::getDataSize(){
00045         return this->myDataSize;
00046 }
00047 
00048 const NetPacket* MessageOut::getPacket(){
00049         if (!this->myPacket){
00050         this->myPacket = new NetPacket(this->myData, this->myDataSize);
00051     }
00052     return this->myPacket;
00053 }
00054 
00055 void MessageOut::writeString(const string &string, Sint16 length){
00056     Uint16 stringLength = string.length();
00057     if (length < 0)
00058     {
00059         // Write the length at the start if not fixed.
00060         write2(stringLength);
00061         length = stringLength;
00062     }
00063     else if (length < stringLength)
00064     {
00065         stringLength = length; // Make sure the length of the string is no longer than specified
00066     }
00067     expandData((this->pos) + length);
00068     memcpy((this->myData) + (this->pos), string.c_str(), stringLength); // Write the actual string.
00069 
00070     if (length > stringLength) // Pad remaining space with zeros.
00071     {
00072         memset((this->myData) + (this->pos) + stringLength, '\0', length - stringLength);
00073     }
00074     this->pos += length;
00075 }
00076 
00077 Uint32 MessageOut::addCRC(){
00078         CRC32 msgCRC;
00079         Uint32 crc;
00080 
00081         msgCRC.Init();
00082         crc = msgCRC.GetCRC(this->myData, (this->pos));
00083 
00084         write4(crc);
00085 
00086         return crc;
00087 }
00088 void MessageOut::expandData(Uint16 size){
00089 
00090         this->myData = (char*)realloc(this->myData, size);
00091         this->myDataSize = size;
00092 }

Generated on Mon Dec 3 04:30:13 2007 for lo-testserver by  doxygen 1.3.9.1