-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtime.cc
More file actions
65 lines (60 loc) · 2.38 KB
/
time.cc
File metadata and controls
65 lines (60 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @file time.cc
* @author Sigma711 (sigma711 at foxmail dot com)
* @brief Implementation of class "TimeServer" which is a simple time server.
* @date 2022-03-03
*
* @copyright Copyright (c) 2022 Sigma711
*
*/
#include "time.h"
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
TimeServer::TimeServer(const taotu::NetAddress& listen_address,
bool should_reuse_port, size_t io_thread_amount)
: event_managers_(), server_(nullptr) {
size_t thread_count = io_thread_amount > 0 ? io_thread_amount : 1;
event_managers_.reserve(thread_count);
for (size_t i = 0; i < thread_count; ++i) {
event_managers_.push_back(new taotu::EventManager);
}
server_ = std::make_unique<taotu::Server>(&event_managers_, listen_address,
should_reuse_port);
server_->SetMessageCallback([this](taotu::Connecting& connection,
taotu::IoBuffer* io_buffer,
taotu::TimePoint time_point) {
this->OnMessageCallback(connection, io_buffer, time_point);
});
}
TimeServer::~TimeServer() {
size_t event_managers_size = event_managers_.size();
for (size_t i = 0; i < event_managers_size; ++i) {
delete event_managers_[i];
}
taotu::END_LOG();
}
void TimeServer::Start() { server_->Start(); }
void TimeServer::OnMessageCallback(taotu::Connecting& connection,
taotu::IoBuffer* io_buffer,
taotu::TimePoint time_point) {
std::string message{io_buffer->RetrieveAllAsString()};
ssize_t msg_len = message.size();
message = message.substr(0, msg_len - 1);
taotu::LOG_DEBUG("Fd(%d) is receiving %u bytes(%s) at %lld.", connection.Fd(),
message.size(),
message.substr(0, message.size() - 1).c_str(),
time_point.GetMicroseconds());
int64_t now_time = time_point.GetMicroseconds();
time_t seconds = static_cast<time_t>(now_time / (1000 * 1000));
struct tm tm_time;
::gmtime_r(&seconds, &tm_time);
char buf[64] = {0};
snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d",
tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec,
static_cast<int>(now_time % (1000 * 1000)));
std::string data(buf);
data += '\n';
connection.Send(data);
}