-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathpacket_proto.cpp
72 lines (59 loc) · 1.76 KB
/
packet_proto.cpp
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
66
67
68
69
70
71
72
/*
* .============.
* // M A K E / \
* // C++ DEV / \
* // E A S Y / \/ \
* ++ ----------. \/\ .
* \\ \ \ /\ /
* \\ \ \ /
* \\ \ \ /
* -============'
*
* Copyright (c) 2023 Hevake and contributors, all rights reserved.
*
* This file is part of cpp-tbox (https://github.com/cpp-main/cpp-tbox)
* Use of this source code is governed by MIT license that can be found
* in the LICENSE file in the root of the source tree. All contributing
* project authors may be found in the CONTRIBUTORS.md file in the root
* of the source tree.
*/
#include "packet_proto.h"
#include <tbox/base/json.hpp>
#include <tbox/base/catch_throw.h>
#include <tbox/util/json.h>
#include <tbox/base/assert.h>
namespace tbox {
namespace jsonrpc {
void PacketProto::sendJson(const Json &js)
{
if (send_data_cb_) {
const auto &json_text = js.dump();
if (is_log_enabled_)
LogTrace("%s send: %s", log_label_.c_str(), json_text.c_str());
send_data_cb_(json_text.data(), json_text.size());
}
}
/**
* 相对于RawStreamProto,它不尝试寻找JSON的结束位置,减少不必要的操作
*/
ssize_t PacketProto::onRecvData(const void *data_ptr, size_t data_size)
{
TBOX_ASSERT(data_ptr != nullptr);
if (data_size < 2)
return 0;
const char *str_ptr = static_cast<const char*>(data_ptr);
const size_t str_len = data_size;
std::string json_text(str_ptr, str_len);
if (is_log_enabled_)
LogTrace("%s recv: %s", log_label_.c_str(), json_text.c_str());
Json js;
bool is_throw = tbox::CatchThrow([&] { js = Json::parse(json_text); });
if (is_throw) {
LogNotice("parse json fail");
return -1;
}
onRecvJson(js);
return str_len;
}
}
}