Tekkotsu Homepage
Demos
Overview
Downloads
Dev. Resources
Reference
Credits

NetworkBuffer.h

Go to the documentation of this file.
00001 #ifndef NETWORK_BUFFER_H_
00002 #define NETWORK_BUFFER_H_
00003 
00004 /*! This is used to incrementally build up a buffer to be sent over
00005  *  the network , so that only one call to the socket write function
00006  *  needs to be made. */
00007 class NetworkBuffer {
00008 public:
00009   
00010   //! constructor
00011   NetworkBuffer() : buf(NULL), offset(0), bufSize(1024) {
00012     buf = new byte[bufSize];
00013   }
00014 
00015   //! destructor
00016   virtual ~NetworkBuffer() {
00017     delete[] buf;
00018   }
00019 
00020   //! Template for adding a single item to the buffer, such as a struct or an int
00021   template <class T> bool addItem(T item) {
00022     if (offset+sizeof(T) > (unsigned int)bufSize)
00023       return false;
00024     
00025     *(T *)(buf+offset) = item;
00026     offset += sizeof(T);
00027     return true;
00028   }
00029 
00030   //! Template for adding a buffer such with a size to the network buffer
00031   bool addBuffer(byte *src, int size) {
00032     if (!addItem(size) || (offset+size > bufSize))
00033       return false;
00034 
00035     memcpy(buf+offset, src, size);
00036     offset += size;
00037     return true;
00038   }
00039 
00040   //! Returns the current size of the buffer
00041   int getSize() { return offset; }
00042 
00043   //! Returns a const pointer to the buffer, for debugging networking code
00044   const byte* getBytes() { return buf; }
00045 
00046   //! Sends the buffer over the given socket
00047   bool send(Socket *sck) {
00048     if (sck->write(buf, offset) != static_cast<int>(offset)) {
00049       std::cout << "Error sending buffer" << std::endl;
00050       return false;
00051     }
00052     
00053     return true;
00054   }
00055   
00056 protected:
00057   byte *buf; //!< the buffer being built
00058   size_t offset; //!< current position in #buf
00059   size_t bufSize; //!< size of memory region at #buf
00060 
00061 private:
00062   NetworkBuffer(NetworkBuffer&); //!< do not call
00063   NetworkBuffer &operator=(const NetworkBuffer&); //!< do not call
00064 };
00065 
00066 #endif

Tekkotsu v5.1CVS
Generated Mon May 9 04:58:45 2016 by Doxygen 1.6.3