PushThread.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "PushThread.h"
  2. // #include <arpa/inet.h>
  3. map<string, CurrentPtr> PushUser::pushUser;
  4. TC_ThreadMutex PushUser::mapMutex;
  5. PushInfoThread::~PushInfoThread()
  6. {
  7. PushUser::pushUser.clear();
  8. }
  9. void PushInfoThread::terminate(void)
  10. {
  11. tars::TC_ThreadLock::Lock sync(*this);
  12. _bTerminate = true;
  13. notifyAll();
  14. }
  15. void PushInfoThread::setPushInfo(const string &sInfo)
  16. {
  17. unsigned int iBuffLength = htonl(sInfo.size()+8);
  18. unsigned char * pBuff = (unsigned char*)(&iBuffLength);
  19. _sPushInfo = "";
  20. for (int i = 0; i<4; ++i)
  21. {
  22. _sPushInfo += *pBuff++;
  23. }
  24. unsigned int iRequestId = htonl(_iId);
  25. unsigned char * pRequestId = (unsigned char*)(&iRequestId);
  26. for (int i = 0; i<4; ++i)
  27. {
  28. _sPushInfo += *pRequestId++;
  29. }
  30. _sPushInfo += sInfo;
  31. }
  32. //定期向客户push消息
  33. void PushInfoThread::run(void)
  34. {
  35. setPushInfo("hello world");
  36. int count = 0;
  37. while (!_bTerminate)
  38. {
  39. ++count;
  40. if(count % 10 == 0)
  41. {
  42. (PushUser::mapMutex).lock();
  43. for (map<string, CurrentPtr>::iterator it = (PushUser::pushUser).begin();
  44. it != (PushUser::pushUser).end(); ++it) {
  45. (it->second)->close();
  46. LOG->debug() << "close" << endl;
  47. }
  48. (PushUser::mapMutex).unlock();
  49. }
  50. else
  51. {
  52. (PushUser::mapMutex).lock();
  53. for (map<string, CurrentPtr>::iterator it = (PushUser::pushUser).begin();
  54. it != (PushUser::pushUser).end(); ++it) {
  55. (it->second)->sendResponse(_sPushInfo.c_str(), _sPushInfo.size());
  56. LOG->debug() << "sendResponse: " << _sPushInfo.size() << endl;
  57. }
  58. (PushUser::mapMutex).unlock();
  59. }
  60. {
  61. TC_ThreadLock::Lock sync(*this);
  62. timedWait(1000);
  63. }
  64. }
  65. }