12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- #ifndef WIN32_LEAN_AND_MEAN
- #define WIN32_LEAN_AND_MEAN
- #endif
- #include <WS2tcpip.h>
- #include <WinSock2.h>
- #include "TimeSync.h"
- #include "../common/iobuffer.h"
- #include "../Protocol/win/Protocol.pb.h"
- #include <time.h>
- void CTimeSync::Start()
- {
- WSAData data;
- WSAStartup(MAKEWORD(2, 2), &data);
- _socket = socket(AF_INET, SOCK_DGRAM, 0);
- sockaddr_in sin;
- sin.sin_family = AF_INET;
- sin.sin_port = htons(23816);
- sin.sin_addr.s_addr = htonl(INADDR_ANY); //inet_addr("192.168.1.9");
- if (::bind(_socket, (sockaddr*)&sin, sizeof(sin)) == -1)
- return ;
- _thread = std::thread(&CTimeSync::Run, this);
- }
- void CTimeSync::Run()
- {
- _run = true;
- while (_run)
- {
- CIOBuffer Buffer;
- sockaddr_in from;
- socklen_t fromlen = sizeof(sockaddr_in);
- int32_t ret=recvfrom(_socket, (char*)Buffer.Buffer, CIOBuffer::IO_BUFFER_SIZE, 0, (sockaddr*)&from, &fromlen);
- if (ret <= 0 || !_run)
- {
- continue;
- }
- MessageHead Head;
- Head.Deserialize(Buffer.Buffer);
- if (Head.Command == RemoNet::CS_SyncTime)
- {
-
- RemoNet::SyncTime Req;
- time_t timer;
- struct tm* t_tm;
- time(&timer);
- Req.set_update_time(true);
- t_tm = localtime(&timer);
- Req.set_tm_hour(t_tm->tm_hour);
- Req.set_tm_mday(t_tm->tm_mday);
- Req.set_tm_min(t_tm->tm_min);
- Req.set_tm_mon(t_tm->tm_mon);
- Req.set_tm_sec(t_tm->tm_sec);
- Req.set_tm_year(t_tm->tm_year);
- Req.set_tm_wday(t_tm->tm_wday);
- Req.set_tm_yday(t_tm->tm_yday);
- Req.set_tm_isdst(t_tm->tm_isdst);
- Head.Command = RemoNet::SC_SyncTime;
- Head.Length = Req.ByteSizeLong();
- Head.Serialize(Buffer.Buffer);
- auto ptr = Buffer.Buffer + MessageHead::Size();
- Req.SerializeToArray(ptr, Head.Length);
- Buffer.Length = MessageHead::Size() + Head.Length;
- int ret = ::sendto(_socket, (char *)Buffer.Buffer, Buffer.Length,0, (sockaddr*)&from, fromlen);
-
- }
- }
- }
- void CTimeSync::Stop()
- {
- _run = false;
- closesocket(_socket);
- _thread.join();
- }
|