TestPushThread.cpp 1.4 KB

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