chatclient.cpp Example File
btchat/chatclient.cpp
#include "chatclient.h"
#include <qbluetoothsocket.h>
ChatClient::ChatClient(QObject *parent)
: QObject(parent), socket(0)
{
}
ChatClient::~ChatClient()
{
stopClient();
}
void ChatClient::startClient(const QBluetoothServiceInfo &remoteService)
{
if (socket)
return;
socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
qDebug() << "Create socket";
socket->connectToService(remoteService);
qDebug() << "ConnectToService done";
connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
}
void ChatClient::stopClient()
{
delete socket;
socket = 0;
}
void ChatClient::readSocket()
{
if (!socket)
return;
while (socket->canReadLine()) {
QByteArray line = socket->readLine();
emit messageReceived(socket->peerName(),
QString::fromUtf8(line.constData(), line.length()));
}
}
void ChatClient::sendMessage(const QString &message)
{
QByteArray text = message.toUtf8() + '\n';
socket->write(text);
}
void ChatClient::connected()
{
emit connected(socket->peerName());
}