summaryrefslogtreecommitdiff
path: root/net/clientnb.cpp
blob: 2e00bd4be985b6041ffbf89de9943aca7247e727 (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <config.h>

#include <atomic>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <mutex>
#include <thread>
#include <assert.h>

#include <Poco/Net/HTMLForm.h>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/FilePartSource.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/Net/WebSocket.h>
#include <Poco/Net/KeyConsoleHandler.h>
#include <Poco/Net/AcceptCertificateHandler.h>
#include <Poco/StreamCopier.h>
#include <Poco/URI.h>
#include <Poco/Util/Application.h>
#include <Poco/Util/HelpFormatter.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Runnable.h>

#include <Util.hpp>

using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::WebSocket;
using Poco::Runnable;
using Poco::Util::Application;

const char *HostName = "127.0.0.1";
constexpr int HttpPortNumber = 9191;
constexpr int SslPortNumber = 9193;

static bool EnableHttps = false;

struct Session
{
private:
    std::string _session_name;
    Poco::Net::HTTPClientSession *_session;

public:
    Session(const char *session_name, bool https = false)
        : _session_name(session_name)
    {
        if (https)
            _session = new Poco::Net::HTTPSClientSession(HostName, SslPortNumber);
        else
            _session = new Poco::Net::HTTPClientSession(HostName, HttpPortNumber);
    }
    ~Session()
    {
        delete _session;
    }

    void sendPing(int i)
    {
        Poco::Net::HTTPRequest request(
            Poco::Net::HTTPRequest::HTTP_POST,
            "/ping/" + _session_name + '/' + std::to_string(i));
        try {
            Poco::Net::HTMLForm form;
            form.setEncoding(Poco::Net::HTMLForm::ENCODING_MULTIPART);
            form.prepareSubmit(request);
            form.write(_session->sendRequest(request));
        }
        catch (const Poco::Exception &e)
        {
            std::cerr << "Failed to write data: " << e.name() <<
                  ' ' << e.message() << '\n';
            throw;
        }
    }

    std::string getResponseString()
    {
        Poco::Net::HTTPResponse response;
        std::istream& responseStream = _session->receiveResponse(response);
        const std::string result(std::istreambuf_iterator<char>(responseStream), {});
        // std::cerr << "Got response '" << result << "'\n";
        return result;
    }

    int getResponseInt()
    {
        int number = 42;

        try {
//            std::cerr << "try to get response\n";
            const std::string result = getResponseString();
            number = std::stoi(result);
        }
        catch (const Poco::Exception &e)
        {
            std::cerr << "Exception converting: " << e.name() <<
                  ' ' << e.message() << '\n';
            throw;
        }
        return number;
    }

    std::shared_ptr<WebSocket> getWebSocket()
    {
        _session->setTimeout(Poco::Timespan(10, 0));
        HTTPRequest request(HTTPRequest::HTTP_GET, "/ws");
        HTTPResponse response;
        return std::shared_ptr<WebSocket>(
            new WebSocket(*_session, request, response));
    }
};

struct ThreadWorker : public Runnable
{
private:
    const char *_domain;
public:
    ThreadWorker(const char *domain = nullptr)
        : _domain(domain)
    {
    }
    virtual void run()
    {
        for (int i = 0; i < 100; ++i)
        {
            Session ping(_domain ? _domain : "init", EnableHttps);
            ping.sendPing(i);
#ifndef NDEBUG
            int back =
#endif
                ping.getResponseInt();
            assert(back == i + 1);
        }
    }
};

struct Client : public Poco::Util::Application
{
    void testPing()
    {
        std::cerr << "testPing\n";
        Session first("init", EnableHttps);
        Session second("init", EnableHttps);

        int count = 42, back;
        first.sendPing(count);
        second.sendPing(count + 1);

        back = first.getResponseInt();
        std::cerr << "testPing: " << back << '\n';
        assert (back == count + 1);

        back = second.getResponseInt();
        std::cerr << "testPing: " << back << '\n';
        assert (back == count + 2);
    }

    void testLadder()
    {
        std::cerr << "testLadder\n";
        ThreadWorker ladder;
        std::thread thread([&ladder]{ladder.run();});
        thread.join();
    }

    void testParallel()
    {
        std::cerr << "testParallel\n";
        const int num = 10;
        std::thread snakes[num];
        ThreadWorker ladders[num];

        for (size_t i = 0; i < num; i++)
            snakes[i] = std::thread([&ladders, i]{ladders[i].run();});

        for (int i = 0; i < num; i++)
            snakes[i].join();
    }

    void testWebsocketPingPong()
    {
        std::cerr << "testWebsocketPingPong\n";
        Session session("ws", EnableHttps);
        std::shared_ptr<WebSocket> ws = session.getWebSocket();

        std::string send = "hello there";
        ws->sendFrame(&send[0], send.length(),
                      WebSocket::SendFlags::FRAME_TEXT);

        for (size_t i = 0; i < 10; i++)
        {
            ws->sendFrame(&i, sizeof(i), WebSocket::SendFlags::FRAME_BINARY);
            size_t back[5];
            int flags = 0;
#ifndef NDEBUG
            int recvd =
#endif
                ws->receiveFrame((void *)back, sizeof(back), flags);
            assert(recvd == sizeof(size_t));
            assert(back[0] == i + 1);
        }
    }

    void testWebsocketEcho()
    {
        std::cerr << "testwebsocketEcho\n";
        Session session("ws", EnableHttps);
        std::shared_ptr<WebSocket> ws = session.getWebSocket();

        std::vector<char> res;

        std::srand(std::time(nullptr));

        std::vector<char> data;
        for (size_t i = 1; i < (1 << 14); ++i)
        {
            data.push_back((char)(std::rand() / (RAND_MAX/256)));
            ws->sendFrame(data.data(), data.size(), WebSocket::SendFlags::FRAME_BINARY);

            res.resize(i);
            int flags;
#ifndef NDEBUG
            int recvd =
#endif
                ws->receiveFrame(res.data(), res.size(), flags);
            assert(recvd == static_cast<int>(i));

            if (i == sizeof(size_t))
            {
                assert(*reinterpret_cast<const size_t*>(res.data()) ==
                       *reinterpret_cast<const size_t*>(data.data()) + 1);
            }
            else
            {
                assert(res == data);
            }
        }
    }

public:
    int main(const std::vector<std::string>& args) override
    {
        EnableHttps = (args.size() > 0 && args[0] == "ssl");
        std::cerr << "Starting " << (EnableHttps ? "HTTPS" : "HTTP") << " client." << std::endl;

        if (EnableHttps)
        {
            Poco::Net::initializeSSL();
            // Just accept the certificate anyway for testing purposes
            Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> invalidCertHandler = new Poco::Net::AcceptCertificateHandler(false);

            Poco::Net::Context::Params sslParams;
            Poco::Net::Context::Ptr sslContext = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, sslParams);
            Poco::Net::SSLManager::instance().initializeClient(nullptr, invalidCertHandler, sslContext);
        }

        testWebsocketPingPong();
        testWebsocketEcho();

        testPing();
        testLadder();
        testParallel();

        return 0;
    }
};

POCO_APP_MAIN(Client)

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */