Packet.h 1.8 KB

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