pqmsgheader.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef PQ_MSGHEADER_H
  2. #define PQ_MSGHEADER_H
  3. #include <QObject>
  4. #include <QtEndian>
  5. namespace PQ {
  6. /***
  7. * 处理tcp分包的包头
  8. */
  9. struct MSGHeader
  10. {
  11. MSGHeader():msgID(0),msgType(0),length(0),compress(0x00),encrypt(0x00)
  12. {}
  13. uint msgID;
  14. ushort msgType;
  15. uint length;
  16. uchar compress;
  17. uchar encrypt;
  18. QByteArray buildArray()
  19. {
  20. QByteArray buffer;
  21. buffer.append("PQ");
  22. char buf[4];
  23. qToBigEndian(msgID,reinterpret_cast<uchar *>(&buf[0]));
  24. buffer.append(&buf[0],4);
  25. qToBigEndian(msgType,reinterpret_cast<uchar *>(&buf[0]));
  26. buffer.append(&buf[0],2);
  27. qToBigEndian(length,reinterpret_cast<uchar *>(&buf[0]));
  28. buffer.append(&buf[0],4);
  29. buffer.append(compress);
  30. buffer.append(encrypt);
  31. buffer.append('p');
  32. buffer.append('q');
  33. return buffer;
  34. }
  35. };
  36. class MSGRead :public QObject
  37. {
  38. Q_OBJECT
  39. public:
  40. MSGRead(bool errorContine = true, QObject * parent = 0);
  41. ~MSGRead(){}
  42. bool readMsg(const QByteArray data);
  43. signals:
  44. void revicedMSG(const MSGHeader & header, QByteArray body);
  45. void hasError();
  46. private:
  47. bool readHeaderCloum(char byte, int max){
  48. byteBuffer[_bytePos] = byte;
  49. _bytePos ++;
  50. return (_bytePos >= max);
  51. }
  52. bool readData(const QByteArray & data,int & pos, int max);
  53. private:
  54. bool _errorContine;
  55. int _status;
  56. int _bytePos;
  57. int _needBytes;
  58. char byteBuffer[4];
  59. MSGHeader header;
  60. QByteArray body;
  61. };
  62. }
  63. #endif // MSGHEADER_H