forked from brainrom/kokovp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleinstance.cpp
74 lines (63 loc) · 2.35 KB
/
singleinstance.cpp
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
/* This is part of KokoVP
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "singleinstance.h"
#include <QLocalSocket>
#include <QLocalServer>
SingleInstance::SingleInstance(QString appName, QObject *parent)
: p_appName(appName), QObject{parent}
{}
bool SingleInstance::connectServer()
{
p_socket = new QLocalSocket(this);
p_socket->connectToServer(p_appName);
bool ret = p_socket->waitForConnected(100); //TODO: subject to change
if (!ret)
qDebug() << "Unable to connect:" << p_socket->errorString();
return ret;
}
void SingleInstance::closeSocket()
{
p_socket->close();
}
bool SingleInstance::hostServer()
{
p_server = new QLocalServer(this);
p_server->removeServer(p_appName); // Asserting, that if no one is listening, then we can remove current server
connect(p_server, &QLocalServer::newConnection, this, &SingleInstance::handleNewConnection);
bool ret = p_server->listen(p_appName);
if(!ret)
qDebug() << "Unable to start server:" << p_server->errorString();
return ret;
}
void SingleInstance::sendMessage(QString msg)
{
p_socket->write(msg.toUtf8());
p_socket->putChar('\n');
p_socket->waitForBytesWritten(100);
}
void SingleInstance::handleNewConnection()
{
while (p_server->hasPendingConnections())
{
QLocalSocket *sock = p_server->nextPendingConnection();
connect(sock, &QLocalSocket::readyRead, this, &SingleInstance::readData);
connect(sock, &QLocalSocket::disconnected, sock, &QLocalSocket::deleteLater);
}
}
void SingleInstance::readData()
{
QLocalSocket *sock = static_cast<QLocalSocket*>(sender());
while (sock->canReadLine())
emit newMessage(sock->readLine());
}