Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members

netmessage.cpp

Go to the documentation of this file.
00001 /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
00002    this file is part of rcssserver3D
00003    Fri May 9 2003
00004    Copyright (C) 2003 Koblenz University
00005    $Id: netmessage.cpp,v 1.2 2004/04/28 14:30:30 rollmark Exp $
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; version 2 of the License.
00010 
00011    This program is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014    GNU General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with this program; if not, write to the Free Software
00018    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
00019 */
00020 #include "netmessage.h"
00021 #include "netbuffer.h"
00022 #include <netinet/in.h>
00023 
00024 using namespace oxygen;
00025 using namespace zeitgeist;
00026 using namespace std;
00027 using namespace boost;
00028 
00029 NetMessage::NetMessage() : Leaf()
00030 {
00031 }
00032 
00033 NetMessage::~NetMessage()
00034 {
00035 }
00036 
00037 void NetMessage::PrepareToSend(std::string& msg)
00038 {
00039     // prefix the message with it's payload length
00040     unsigned int len = htonl(msg.size());
00041     string prefix((const char*)&len,sizeof(unsigned int));
00042     msg = prefix + msg;
00043 }
00044 
00045 bool NetMessage::Extract(shared_ptr<NetBuffer> buffer, std::string& msg)
00046 {
00047     // a message is prefixed with it's payload length
00048     const unsigned int preSz = sizeof(unsigned int);
00049     string& data = buffer->GetData();
00050 
00051     if (data.size() < preSz)
00052         {
00053             return false;
00054         }
00055 
00056     unsigned int msgLen = ntohl((*(unsigned int*)data.data()));
00057 
00058     if (data.size() < (msgLen + preSz))
00059         {
00060             // incomplete message
00061             return false;
00062         }
00063 
00064     // copy to msg and cut from buffer
00065     msg = string(data.c_str() + preSz, msgLen);
00066     data.erase(0, preSz + msgLen);
00067 
00068     // zero terminate received data
00069     msg += '\0';
00070 
00071     return true;
00072 }

Generated on Thu Apr 6 15:25:39 2006 for rcssserver3d by  doxygen 1.4.4