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
79
80
81
82
83
84
|
// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "chatclient.h"
#include <QtCore/qmetaobject.h>
ChatClient::ChatClient(QObject *parent)
: QObject(parent)
{
}
ChatClient::~ChatClient()
{
stopClient();
}
//! [startClient]
void ChatClient::startClient(const QBluetoothServiceInfo &remoteService)
{
if (socket)
return;
// Connect to service
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
qDebug() << "Create socket";
socket->connectToService(remoteService);
qDebug() << "ConnectToService done";
connect(socket, &QBluetoothSocket::readyRead, this, &ChatClient::readSocket);
connect(socket, &QBluetoothSocket::connected, this, QOverload<>::of(&ChatClient::connected));
connect(socket, &QBluetoothSocket::disconnected, this, &ChatClient::disconnected);
connect(socket, &QBluetoothSocket::errorOccurred, this, &ChatClient::onSocketErrorOccurred);
}
//! [startClient]
//! [stopClient]
void ChatClient::stopClient()
{
delete socket;
socket = nullptr;
}
//! [stopClient]
//! [readSocket]
void ChatClient::readSocket()
{
if (!socket)
return;
while (socket->canReadLine()) {
QByteArray line = socket->readLine().trimmed();
emit messageReceived(socket->peerName(),
QString::fromUtf8(line.constData(), line.length()));
}
}
//! [readSocket]
//! [sendMessage]
void ChatClient::sendMessage(const QString &message)
{
QByteArray text = message.toUtf8() + '\n';
socket->write(text);
}
//! [sendMessage]
void ChatClient::onSocketErrorOccurred(QBluetoothSocket::SocketError error)
{
if (error == QBluetoothSocket::SocketError::NoSocketError)
return;
QMetaEnum metaEnum = QMetaEnum::fromType<QBluetoothSocket::SocketError>();
QString errorString = socket->peerName() + QLatin1Char(' ')
+ metaEnum.valueToKey(static_cast<int>(error)) + QLatin1String(" occurred");
emit socketErrorOccurred(errorString);
}
//! [connected]
void ChatClient::connected()
{
emit connected(socket->peerName());
}
//! [connected]
|