This repository has been archived by the owner on Oct 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.h
79 lines (73 loc) · 2.47 KB
/
client.h
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
73
74
75
76
77
78
79
/* Copyright (c) 2017-2018, EPFL/Blue Brain Project
*
* This file is part of Rockets <https://github.com/BlueBrain/Rockets>
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License version 3.0 as published
* by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef ROCKETS_JSONRPC_CLIENT_H
#define ROCKETS_JSONRPC_CLIENT_H
#include <rockets/jsonrpc/receiver.h>
#include <rockets/jsonrpc/requester.h>
namespace rockets
{
namespace jsonrpc
{
/**
* JSON-RPC client.
*
* The client can be used over any communication channel that provides the
* following methods:
*
* - void sendText(std::string message);
* Used to send notifications and requests to the server.
*
* - void handleText(ws::MessageCallback callback);
* Used to register a callback for processing the responses from the server
* when they arrive (non-blocking requests) as well as receiving
* notifications.
*/
template <typename Communicator>
class Client : public Requester, public Receiver
{
public:
Client(Communicator& comm)
: communicator{comm}
{
communicator.handleText(
[ this, thisStatus =
std::weak_ptr<bool>{status} ](const Request& request_) {
// Prevent access to *this* by a callback after the Client has
// been destroyed (in non-multithreaded contexts).
if (!thisStatus.expired())
{
if (!processResponse(request_.message))
_processNotification(request_);
}
return std::string();
});
}
private:
/** Notifier::_send */
void _send(std::string json) final
{
communicator.sendText(std::move(json));
}
void _processNotification(const Request& request_) { process(request_); }
Communicator& communicator;
std::shared_ptr<bool> status = std::make_shared<bool>(true);
};
}
}
#endif