Packet.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. template<int N>
  21. bool readString(StringBuffer<N>& s) {
  22. uint16 end;
  23. if(readU16(end)) {
  24. return true;
  25. }
  26. s.clear();
  27. for(unsigned int i = 0; i < end; i++) {
  28. int8 c;
  29. if(readS8(c)) {
  30. return true;
  31. }
  32. s.append(c);
  33. }
  34. return false;
  35. }
  36. };
  37. class OutPacket {
  38. ENetPacket* packet;
  39. unsigned int index;
  40. int channel;
  41. friend class Client;
  42. friend class Server;
  43. OutPacket(unsigned int size, int flags, int channel);
  44. public:
  45. static OutPacket reliable(unsigned int size);
  46. static OutPacket sequenced(unsigned int size);
  47. static OutPacket unsequenced(unsigned int size);
  48. ~OutPacket();
  49. OutPacket(const OutPacket& other);
  50. OutPacket(OutPacket&& other);
  51. OutPacket& operator=(OutPacket other);
  52. void writeU8(uint8 u);
  53. void writeU16(uint16 u);
  54. void writeU32(uint32 u);
  55. void writeS8(int8 s);
  56. void writeS16(int16 s);
  57. void writeS32(int32 s);
  58. template<int N>
  59. void writeString(const StringBuffer<N>& s) {
  60. uint16 end = s.getLength() > 65535 ? 65535 : s.getLength();
  61. writeU16(end);
  62. for(unsigned int i = 0; i < end; i++) {
  63. writeS8(s[i]);
  64. }
  65. }
  66. private:
  67. void write(const void* buffer, unsigned int length);
  68. };
  69. #endif