Packet.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #ifndef PACKET_H
  2. #define PACKET_H
  3. #include "network/ENet.h"
  4. #include "utils/StringBuffer.h"
  5. #include "utils/Types.h"
  6. class InPacket {
  7. ENetPacket* packet;
  8. unsigned int index;
  9. friend class Client;
  10. friend class Server;
  11. InPacket(ENetPacket* packet);
  12. bool read(void* buffer, unsigned int length);
  13. public:
  14. bool readU8(uint8& u);
  15. bool readU16(uint16& u);
  16. bool readU32(uint32& u);
  17. bool readS8(int8& s);
  18. bool readS16(int16& s);
  19. bool readS32(int32& s);
  20. bool readFloat(float& f);
  21. template<int N>
  22. bool readString(StringBuffer<N>& s) {
  23. uint16 end;
  24. if(readU16(end)) {
  25. return true;
  26. }
  27. s.clear();
  28. for(unsigned int i = 0; i < end; i++) {
  29. int8 c;
  30. if(readS8(c)) {
  31. return true;
  32. }
  33. s.append(c);
  34. }
  35. return false;
  36. }
  37. };
  38. class OutPacket {
  39. ENetPacket* packet;
  40. unsigned int index;
  41. int channel;
  42. friend class Client;
  43. friend class Server;
  44. OutPacket(unsigned int size, int flags, int channel);
  45. public:
  46. static OutPacket reliable(unsigned int size);
  47. static OutPacket sequenced(unsigned int size);
  48. static OutPacket unsequenced(unsigned int size);
  49. ~OutPacket();
  50. OutPacket(const OutPacket& other);
  51. OutPacket(OutPacket&& other);
  52. OutPacket& operator=(OutPacket other);
  53. void writeU8(uint8 u);
  54. void writeU16(uint16 u);
  55. void writeU32(uint32 u);
  56. void writeS8(int8 s);
  57. void writeS16(int16 s);
  58. void writeS32(int32 s);
  59. void writeFloat(float f);
  60. template<int N>
  61. void writeString(const StringBuffer<N>& s) {
  62. uint16 end = s.getLength() > 65535 ? 65535 : s.getLength();
  63. writeU16(end);
  64. for(unsigned int i = 0; i < end; i++) {
  65. writeS8(s[i]);
  66. }
  67. }
  68. private:
  69. void write(const void* buffer, unsigned int length);
  70. };
  71. #endif