summaryrefslogtreecommitdiff
path: root/graphics/asymptote/LspCpp/examples/WebsocketExample.cpp
blob: d79569f536aa365504c52079c51891f0d6a9c4bc (plain)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296

#include "LibLsp/JsonRpc/WebSocketServer.h"
#include "LibLsp/lsp/textDocument/signature_help.h"
#include "LibLsp/lsp/general/initialize.h"
#include "LibLsp/lsp/ProtocolJsonHandler.h"
#include "LibLsp/lsp/textDocument/typeHierarchy.h"
#include "LibLsp/lsp/AbsolutePath.h"
#include "LibLsp/lsp/textDocument/resolveCompletionItem.h"
#include <network/uri.hpp>


#include "LibLsp/JsonRpc/Endpoint.h"
#include "LibLsp/JsonRpc/stream.h"
#include "LibLsp/JsonRpc/TcpServer.h"
#include "LibLsp/lsp/textDocument/document_symbol.h"
#include "LibLsp/lsp/workspace/execute_command.h"

#include <boost/filesystem.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/dispatch.hpp>
#include <boost/asio/strand.hpp>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>

#include <boost/beast/version.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/dispatch.hpp>
#include "LibLsp/JsonRpc/Endpoint.h"
#include "LibLsp/JsonRpc/RemoteEndPoint.h"
#include "LibLsp/JsonRpc/stream.h"
#include "LibLsp/lsp/ProtocolJsonHandler.h"

namespace beast = boost::beast;         // from <boost/beast.hpp>
namespace http = beast::http;           // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio;            // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>

//------------------------------------------------------------------------------

std::string _address = "127.0.0.1";
std::string _port = "9333";




using namespace std;
class DummyLog :public lsp::Log
{
public:

    void log(Level level, std::wstring&& msg)
    {
        std::wcout << msg << std::endl;
    };
    void log(Level level, const std::wstring& msg)
    {
        std::wcout << msg << std::endl;
    };
    void log(Level level, std::string&& msg)
    {
        std::cout << msg << std::endl;
    };
    void log(Level level, const std::string& msg)
    {
        std::cout << msg << std::endl;
    };
};



// Sends a WebSocket message and prints the response
class Client : public std::enable_shared_from_this<Client>
{
    net::io_context ioc;
    tcp::resolver resolver_;
    websocket::stream<beast::tcp_stream> ws_;
    beast::flat_buffer buffer_;
    std::string host_;
    std::string user_agent_;
    std::shared_ptr < lsp::ProtocolJsonHandler >  protocol_json_handler = std::make_shared< lsp::ProtocolJsonHandler>();
    DummyLog _log;
	
    std::shared_ptr<GenericEndpoint>  endpoint = std::make_shared<GenericEndpoint>(_log);
	
    std::shared_ptr<lsp::websocket_stream_wrapper>  proxy_;
public:
   RemoteEndPoint point;

public:
    // Resolver and socket require an io_context
    explicit
        Client()
        : resolver_(net::make_strand(ioc))
        , ws_(net::make_strand(ioc)),point(protocol_json_handler, endpoint, _log)
    {
        proxy_ = std::make_shared<lsp::websocket_stream_wrapper>(ws_);
 
    }

    // Start the asynchronous operation
    void
        run(
            char const* host,
            char const* port, char const* user_agent)
    {
        // Save these for later
        host_ = host;
        user_agent_ = user_agent;
        // Look up the domain name
        resolver_.async_resolve(
            host,
            port,
            beast::bind_front_handler(
                &Client::on_resolve,
                shared_from_this()));
        std::thread([&]
        {
               ioc.run();
        }).detach();
        while (!point.IsWorking())
        {
            std::this_thread::sleep_for(std::chrono::milliseconds (50));
        }
    }
    
    void
        on_resolve(
            beast::error_code ec,
            tcp::resolver::results_type results)
    {
        if (ec)
            return;

        // Set the timeout for the operation
        beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(30));

        // Make the connection on the IP address we get from a lookup
        beast::get_lowest_layer(ws_).async_connect(
            results,
            beast::bind_front_handler(
                &Client::on_connect,
                shared_from_this()));
    }

    void
        on_connect(beast::error_code ec, tcp::resolver::results_type::endpoint_type)
    {
        if (ec)
            return;

        // Turn off the timeout on the tcp_stream, because
        // the websocket stream has its own timeout system.
        beast::get_lowest_layer(ws_).expires_never();

        // Set suggested timeout settings for the websocket
        ws_.set_option(
            websocket::stream_base::timeout::suggested(
                beast::role_type::client));

        // Set a decorator to change the User-Agent of the handshake
        ws_.set_option(websocket::stream_base::decorator(
            [=](websocket::request_type& req)
            {
                req.set(http::field::user_agent,
                    user_agent_.c_str());
            }));

        // Perform the websocket handshake
        ws_.async_handshake(host_, "/",
            beast::bind_front_handler(
                &Client::on_handshake,
                shared_from_this()));
    }

    void
        on_handshake(beast::error_code ec)
    {
        if (ec)
            return;

        // Send the message
    

        point.startProcessingMessages(proxy_, proxy_);
        // Read a message into our buffer
        ws_.async_read(
            buffer_,
            beast::bind_front_handler(
                &Client::on_read,
                shared_from_this()));
    }


    void
        on_read(
            beast::error_code ec,
            std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        if (ec)
            return;

        char* data = reinterpret_cast<char*>(buffer_.data().data());
        std::vector<char> elements(data, data + bytes_transferred);
        buffer_.clear();
        proxy_->on_request.EnqueueAll(std::move(elements), false);
        
        ws_.async_read(
            buffer_,
            beast::bind_front_handler(
                &Client::on_read,
                shared_from_this()));
    }

    void
        on_close(beast::error_code ec)
    {
        if (ec)
            return;

        // If we get here then the connection is closed gracefully

        // The make_printable() function helps print a ConstBufferSequence
        std::cout << beast::make_printable(buffer_.data()) << std::endl;
    }
};

class Server
{
public:
    Server(const std::string& user_agent) : server(user_agent,_address, _port, protocol_json_handler, endpoint, _log)
    {
        server.point.registerHandler(
            [&](const td_initialize::request& req)
            {
                td_initialize::response rsp;
                CodeLensOptions code_lens_options;
                code_lens_options.resolveProvider = true;
                rsp.result.capabilities.codeLensProvider = code_lens_options;
                return rsp;
		});
        std::thread([&]()
            {
                server.run();
            }).detach();
    }
    ~Server()
    {
        server.stop();
    }
    std::shared_ptr <  lsp::ProtocolJsonHandler >  protocol_json_handler = std::make_shared < lsp::ProtocolJsonHandler >();
    DummyLog _log;
    
    std::shared_ptr < GenericEndpoint >  endpoint = std::make_shared<GenericEndpoint>(_log);
    lsp::WebSocketServer server;

};

int main()
{
    std::string user_agent = std::string(BOOST_BEAST_VERSION_STRING) +" websocket-server-async";
    Server server(user_agent);
   
    auto client = std::make_shared<Client>();
    user_agent = std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-async";
    client->run(_address.c_str(), _port.c_str(), user_agent.c_str());
	
    td_initialize::request req;

    auto rsp = client->point.waitResponse(req);
    if (rsp)
    {
        std::cout << rsp->ToJson() << std::endl;
    }
    return 0;
}