pineapple-music/singleapplicationmanager.cpp
2020-04-11 19:54:51 +08:00

58 lines
1.5 KiB
C++

#include "singleapplicationmanager.h"
#include <QDataStream>
#include <QLocalServer>
#include <QLocalSocket>
SingleApplicationManager::SingleApplicationManager(QString applicationKey, QObject *parent)
: QObject(parent)
, m_applicationKey(applicationKey)
{
}
void SingleApplicationManager::on_localSocket_newConnection()
{
QScopedPointer<QLocalSocket> socket(m_localServer->nextPendingConnection());
if (socket) {
socket->waitForReadyRead(500);
QDataStream dataStream(socket.data());
QVariant data;
dataStream.startTransaction();
dataStream >> data;
dataStream.commitTransaction();
emit dataReached(data);
}
}
void SingleApplicationManager::createSingleInstance()
{
m_localServer = new QLocalServer(this);
connect(m_localServer, &QLocalServer::newConnection, this, &SingleApplicationManager::on_localSocket_newConnection);
if (!m_localServer->listen(m_applicationKey)) {
if (m_localServer->serverError() == QAbstractSocket::AddressInUseError) {
QLocalServer::removeServer(m_applicationKey);
m_localServer->listen(m_applicationKey);
}
}
}
bool SingleApplicationManager::checkSingleInstance(QVariant data)
{
QLocalSocket socket;
socket.connectToServer(m_applicationKey);
if (socket.waitForConnected(500)) {
QDataStream dataStream(&socket);
dataStream << data;
socket.waitForBytesWritten();
socket.close();
return true;
}
return false;
}