JSON-RPC 2.0
JSON-RPC 2.0 Modern C++ Library
Loading...
Searching...
No Matches
server.cpp
Go to the documentation of this file.
2
3#include <spdlog/spdlog.h>
4
5namespace jsonrpc::server {
6
7Server::Server(std::unique_ptr<transport::Transport> transport)
8 : transport_(std::move(transport)) {
9 dispatcher_ = std::make_unique<Dispatcher>();
10 spdlog::info("Server initialized with transport");
11}
12
14 spdlog::info("Server starting");
15 running_.store(true);
16 Listen();
17}
18
20 spdlog::info("Server stopping");
21 running_.store(false);
22}
23
24auto Server::IsRunning() const -> bool {
25 return running_.load();
26}
27
28void Server::Listen() {
29 if (!dispatcher_) {
30 spdlog::error("Dispatcher is not set.");
31 return;
32 }
33 if (!transport_) {
34 spdlog::error("Transport is not set.");
35 return;
36 }
37
38 while (IsRunning()) {
39 std::string request = transport_->ReceiveMessage();
40 if (request.empty()) {
41 continue;
42 }
43 std::optional<std::string> response = dispatcher_->DispatchRequest(request);
44 if (response.has_value()) {
45 transport_->SendMessage(response.value());
46 }
47 }
48}
49
51 const std::string &method, const MethodCallHandler &handler) {
52 dispatcher_->RegisterMethodCall(method, handler);
53}
54
56 const std::string &method, const NotificationHandler &handler) {
57 dispatcher_->RegisterNotification(method, handler);
58}
59
60} // namespace jsonrpc::server
void Start()
Starts the server to handle incoming JSON-RPC requests.
Definition server.cpp:13
auto IsRunning() const -> bool
Checks if the server is currently running.
Definition server.cpp:24
void RegisterMethodCall(const std::string &method, const MethodCallHandler &handler)
Registers an RPC method handler with the dispatcher.
Definition server.cpp:50
void RegisterNotification(const std::string &method, const NotificationHandler &handler)
Registers an RPC notification handler with the dispatcher.
Definition server.cpp:55
Server(std::unique_ptr< transport::Transport > transport)
Constructs a Server with the specified transport.
Definition server.cpp:7
void Stop()
Stops the server from handling requests.
Definition server.cpp:19
std::function< void(const std::optional< nlohmann::json > &)> NotificationHandler
Type alias for notification handler functions.
Definition types.hpp:26
std::function< nlohmann::json(const std::optional< nlohmann::json > &)> MethodCallHandler
Type alias for method call handler functions.
Definition types.hpp:17