TimeSync.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #ifndef WIN32_LEAN_AND_MEAN
  2. #define WIN32_LEAN_AND_MEAN
  3. #endif
  4. #include <WS2tcpip.h>
  5. #include <WinSock2.h>
  6. #include "TimeSync.h"
  7. #include "../common/iobuffer.h"
  8. #include "../Protocol/win/Protocol.pb.h"
  9. #include <time.h>
  10. void CTimeSync::Start()
  11. {
  12. WSAData data;
  13. WSAStartup(MAKEWORD(2, 2), &data);
  14. _socket = socket(AF_INET, SOCK_DGRAM, 0);
  15. sockaddr_in sin;
  16. sin.sin_family = AF_INET;
  17. sin.sin_port = htons(23816);
  18. sin.sin_addr.s_addr = htonl(INADDR_ANY); //inet_addr("192.168.1.9");
  19. if (::bind(_socket, (sockaddr*)&sin, sizeof(sin)) == -1)
  20. return ;
  21. _thread = std::thread(&CTimeSync::Run, this);
  22. }
  23. void CTimeSync::Run()
  24. {
  25. _run = true;
  26. while (_run)
  27. {
  28. CIOBuffer Buffer;
  29. sockaddr_in from;
  30. socklen_t fromlen = sizeof(sockaddr_in);
  31. int32_t ret=recvfrom(_socket, (char*)Buffer.Buffer, CIOBuffer::IO_BUFFER_SIZE, 0, (sockaddr*)&from, &fromlen);
  32. if (ret <= 0 || !_run)
  33. {
  34. continue;
  35. }
  36. MessageHead Head;
  37. Head.Deserialize(Buffer.Buffer);
  38. if (Head.Command == RemoNet::CS_SyncTime)
  39. {
  40. RemoNet::SyncTime Req;
  41. time_t timer;
  42. struct tm* t_tm;
  43. time(&timer);
  44. Req.set_update_time(true);
  45. t_tm = localtime(&timer);
  46. Req.set_tm_hour(t_tm->tm_hour);
  47. Req.set_tm_mday(t_tm->tm_mday);
  48. Req.set_tm_min(t_tm->tm_min);
  49. Req.set_tm_mon(t_tm->tm_mon);
  50. Req.set_tm_sec(t_tm->tm_sec);
  51. Req.set_tm_year(t_tm->tm_year);
  52. Req.set_tm_wday(t_tm->tm_wday);
  53. Req.set_tm_yday(t_tm->tm_yday);
  54. Req.set_tm_isdst(t_tm->tm_isdst);
  55. Head.Command = RemoNet::SC_SyncTime;
  56. Head.Length = Req.ByteSizeLong();
  57. Head.Serialize(Buffer.Buffer);
  58. auto ptr = Buffer.Buffer + MessageHead::Size();
  59. Req.SerializeToArray(ptr, Head.Length);
  60. Buffer.Length = MessageHead::Size() + Head.Length;
  61. int ret = ::sendto(_socket, (char *)Buffer.Buffer, Buffer.Length,0, (sockaddr*)&from, fromlen);
  62. }
  63. }
  64. }
  65. void CTimeSync::Stop()
  66. {
  67. _run = false;
  68. closesocket(_socket);
  69. _thread.join();
  70. }