-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcpclient.cpp
More file actions
63 lines (55 loc) · 1.37 KB
/
tcpclient.cpp
File metadata and controls
63 lines (55 loc) · 1.37 KB
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
#include "tcpclient.h"
#include <memory>
#include <QTcpSocket>
#include <QDebug>
#include <QObject>
#include <QHostAddress>
TcpClient::TcpClient(const QString& host, quint32 port)
: m_socket(std::make_unique<QTcpSocket>()),
m_host(host),
m_port(port)
{
QObject::connect(m_socket.get(), &QTcpSocket::connected, this, &TcpClient::connected);
QObject::connect(m_socket.get(), &QTcpSocket::disconnected, this, &TcpClient::disconnected);
QObject::connect(m_socket.get(), &QTcpSocket::readyRead, this, [this]() {
m_buffer.append(m_socket->readAll());
auto messages = m_buffer.split("\n");
if(not messages.empty())
{
m_buffer = messages.back();
messages.pop_back();
for(auto& message : messages)
{
emit messageReceived(message);
}
}
});
}
TcpClient::~TcpClient()
{
disconnect();
}
void TcpClient::connect()
{
m_socket->connectToHost(m_host, m_port);
}
void TcpClient::disconnect()
{
m_socket->disconnectFromHost();
m_socket->abort();
}
void TcpClient::setPort(quint32 port)
{
m_port = port;
}
void TcpClient::setIpAddr(const QString& ip)
{
m_host = ip;
}
void TcpClient::sendMessage(const QByteArray& msg)
{
if (m_socket && m_socket->state() == QAbstractSocket::ConnectedState)
{
m_socket->write(msg );
}
}