File: main.cpp

package info (click to toggle)
qcoro 0.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,700 kB
  • sloc: cpp: 8,573; python: 32; xml: 26; makefile: 23; sh: 15
file content (66 lines) | stat: -rw-r--r-- 1,633 bytes parent folder | download | duplicates (3)
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
#include "qcoroiodevice.h"
#include "qcorotask.h"

#include <QCoreApplication>
#include <QHostAddress>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>

#include <chrono>
#include <iostream>

using namespace std::chrono_literals;

class Server : public QObject {
    Q_OBJECT
public:
    explicit Server(QHostAddress addr, uint16_t port) {
        mServer.listen(addr, port);
        connect(&mServer, &QTcpServer::newConnection, this, &Server::handleConnection);
    }

private Q_SLOTS:
    QCoro::Task<> handleConnection() {
        auto socket = mServer.nextPendingConnection();
        while (socket->isOpen()) {
            const auto data = co_await socket;
            socket->write("PONG: " + data);
        }
    }

private:
    QTcpServer mServer;
};

class Client : public QObject {
    Q_OBJECT
public:
    explicit Client(QHostAddress addr, uint16_t port) {
        mSocket.connectToHost(addr, port);
        connect(&mTimer, &QTimer::timeout, this, &Client::sendPing);
        mTimer.start(300ms);
    }

private Q_SLOTS:
    QCoro::Task<> sendPing() {
        std::cout << "Sending ping..." << std::endl;
        mSocket.write(QByteArray("PING #") + QByteArray::number(++mPing));
        const auto response = co_await mSocket;
        std::cout << "Received pong: " << response.constData() << std::endl;
    }

private:
    int mPing = 0;
    QTcpSocket mSocket;
    QTimer mTimer;
};

int main(int argc, char **argv) {
    QCoreApplication app{argc, argv};
    Server server{QHostAddress::LocalHost, 6666};
    Client client{QHostAddress::LocalHost, 6666};
    return app.exec();
}

#include "main.moc"