File: TCPClient.cpp

package info (click to toggle)
js8call 2.2.0%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 22,416 kB
  • sloc: cpp: 563,285; f90: 9,265; ansic: 937; python: 132; sh: 93; makefile: 6
file content (78 lines) | stat: -rw-r--r-- 1,425 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
67
68
69
70
71
72
73
74
75
76
77
78
#include "TCPClient.h"

#include <QTcpSocket>
#include <QDebug>

#include "pimpl_impl.hpp"

#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 connectToHost(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_->connectToHost(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();
}