1 | // Copyright (C) 2024 Jarek Kobus |
2 | // Copyright (C) 2024 The Qt Company Ltd. |
3 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
4 | |
5 | #include "tcpsocket.h" |
6 | |
7 | QT_BEGIN_NAMESPACE |
8 | |
9 | namespace Tasking { |
10 | |
11 | void TcpSocket::start() |
12 | { |
13 | if (m_socket) { |
14 | qWarning(msg: "The TcpSocket is already running. Ignoring the call to start()." ); |
15 | return; |
16 | } |
17 | if (m_address.isNull()) { |
18 | qWarning(msg: "Can't start the TcpSocket with invalid address. " |
19 | "Stopping with an error." ); |
20 | m_error = QAbstractSocket::HostNotFoundError; |
21 | emit done(result: DoneResult::Error); |
22 | return; |
23 | } |
24 | |
25 | m_socket.reset(p: new QTcpSocket); |
26 | connect(sender: m_socket.get(), signal: &QAbstractSocket::errorOccurred, context: this, |
27 | slot: [this](QAbstractSocket::SocketError error) { |
28 | m_error = error; |
29 | m_socket->disconnect(); |
30 | emit done(result: DoneResult::Error); |
31 | m_socket.release()->deleteLater(); |
32 | }); |
33 | connect(sender: m_socket.get(), signal: &QAbstractSocket::connected, context: this, slot: [this] { |
34 | if (!m_writeData.isEmpty()) |
35 | m_socket->write(data: m_writeData); |
36 | emit started(); |
37 | }); |
38 | connect(sender: m_socket.get(), signal: &QAbstractSocket::disconnected, context: this, slot: [this] { |
39 | m_socket->disconnect(); |
40 | emit done(result: DoneResult::Success); |
41 | m_socket.release()->deleteLater(); |
42 | }); |
43 | |
44 | m_socket->connectToHost(address: m_address, port: m_port); |
45 | } |
46 | |
47 | TcpSocket::~TcpSocket() |
48 | { |
49 | if (m_socket) { |
50 | m_socket->disconnect(); |
51 | m_socket->abort(); |
52 | } |
53 | } |
54 | |
55 | TcpSocketTaskAdapter::TcpSocketTaskAdapter() |
56 | { |
57 | connect(sender: task(), signal: &TcpSocket::done, context: this, slot: &TaskInterface::done); |
58 | } |
59 | |
60 | void TcpSocketTaskAdapter::start() |
61 | { |
62 | task()->start(); |
63 | } |
64 | |
65 | } // namespace Tasking |
66 | |
67 | QT_END_NAMESPACE |
68 | |