File: TCPClient.cpp

package info (click to toggle)
js8call 2.5.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 24,724 kB
  • sloc: cpp: 562,639; sh: 898; python: 132; ansic: 102; makefile: 4
file content (69 lines) | stat: -rw-r--r-- 1,544 bytes parent folder | download | duplicates (2)
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
#include "TCPClient.h"

#include <QDebug>
#include <QTcpSocket>

#include "JS8_Include/pimpl_impl.h"

#include "moc_TCPClient.cpp"

class TCPClient::impl : public QTcpSocket {
    Q_OBJECT

  public:
    using port_type = quint16;

    impl(TCPClient *self) : self_{self} {}

    ~impl() {}

    bool isConnected(QString host, port_type port) {
        if (host_ != host || port_ != port) {
            disconnectFromHost();
            return false;
        }
        return state() == QTcpSocket::ConnectedState;
    }

    void connectToHostPort(QString host, port_type port) {
        host_ = host;
        port_ = port;

        QTcpSocket::connectToHost(host_, port_);
    }

    qint64 send(QByteArray const &message, bool crlf) {
        return write(message + (crlf ? "\r\f" : ""));
    }

    TCPClient *self_;
    QString host_;
    port_type port_;
};

#include "TCPClient.moc"

TCPClient::TCPClient(QObject *parent) : QObject(parent), m_{this} {}

bool TCPClient::ensureConnected(QString host, port_type port, int msecs) {
    if (!m_->isConnected(host, port)) {
        m_->connectToHostPort(host, port);
    }

    return m_->waitForConnected(msecs);
}

bool TCPClient::sendNetworkMessage(QString host, port_type port,
                                   QByteArray const &message, bool crlf,
                                   int msecs) {
    if (!ensureConnected(host, port, msecs)) {
        return false;
    }

    qint64 n = m_->send(message, crlf);
    if (n <= 0) {
        return false;
    }

    return m_->flush();
}