00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00025
00026
00027 #ifndef Packet_H
00028 #define Packet_H
00029
00030 #include "H3DNetworkingUtils/Config.h"
00031 #include "H3DNetworkingUtils/sockwrap.h"
00032 #include "H3DNetworkingUtils/lockwrap.h"
00033 #include "H3DNetworkingUtils/PacketSequenceChecker.h"
00034
00035 namespace H3DNetworkingUtils {
00036
00049
00058
00059 class H3D_NETWORKING_UTILS_DLL_SPEC Packet {
00060 public:
00062 Packet(int sz = 128);
00063
00065 Packet(Packet const & other);
00066
00068 Packet & operator=(Packet const & other);
00069
00070 virtual ~Packet() {delete [] buffer_head; }
00071
00073 void write(void * data, int num) {
00074 stretchBuffer(num);
00075 memcpy(&buffer_payload[payload_size], data, num);
00076 payload_size += num;
00077 }
00078
00081 bool send(TCPSock * sockP);
00082
00085 bool send(UDPSock * sockP, InetAddr * remote_end);
00086
00088 void clear() {payload_size = 0;}
00089
00092 bool receive(TCPSock * sockP);
00093
00097 int receive(UDPSock * sockP, InetAddr * remote_end);
00098
00100 void read(void * dest, int num_bytes) {
00101 memcpy(dest, &buffer_payload[get_pos], num_bytes);
00102 get_pos += num_bytes;
00103 }
00104
00106 int readInt16() const;
00107
00109 void writeInt16(int const & val);
00110
00113 bool isHeartBeat() const {return (getId() == HEART_BEAT_ID); }
00114
00117 void setHeartBeat();
00118
00120 int getId() const;
00121
00123 short getSeqNum() const;
00124
00126 void setId(int id);
00127
00129 void setSeqNum(short seq);
00130
00132 void stretchBuffer(u_int extra_size);
00133
00134 private:
00135
00136
00137
00138 char * buffer_head;
00139 char * buffer_payload;
00140 mutable int get_pos;
00141 bool keep_data;
00142
00143 static const int HEART_BEAT_ID;
00144 static const char CR;
00145 static const char LF;
00146 int payload_size;
00147 int max_payload_size;
00148 static const int HEADER_SIZE;
00149 static const int PACKET_SIZE_OFFSET;
00150 static const int PACKET_SIZE_SIZE;
00151 static const int SEQ_NUM_SIZE;
00152 static const int ID_SIZE;
00153 static const int SEQ_NUM_OFFSET;
00154 static const int ID_OFFSET;
00155
00156 union {
00157 int v;
00158 char sz[4];
00159 } enc_int;
00160 union {
00161 int v;
00162 char sz[4];
00163 } dec_int;
00164
00165 u_int buffer_size;
00166 };
00167
00168 }
00169
00170 #endif