本文整理汇总了C++中QLocalSocket::waitForConnected方法的典型用法代码示例。如果您正苦于以下问题:C++ QLocalSocket::waitForConnected方法的具体用法?C++ QLocalSocket::waitForConnected怎么用?C++ QLocalSocket::waitForConnected使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QLocalSocket
的用法示例。
在下文中一共展示了QLocalSocket::waitForConnected方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// assure one application instance
QString uniqueID( HomePrism_UUID );
QLocalSocket socket;
socket.connectToServer(uniqueID);
if (socket.waitForConnected(500))
{
QMessageBox::critical(0, QObject::tr("HomePrism"),
QObject::tr("Another HomePrism is already running. Will exit now."));
return EXIT_FAILURE; // Exit already a process running
}
// some app specific params
QCoreApplication::setApplicationName( HomePrism_TITLE );
QCoreApplication::setOrganizationName("DKFZ");
// start
HomePrism homePrismWindow;
homePrismWindow.setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
homePrismWindow.size(),
qApp->desktop()->availableGeometry()
));
homePrismWindow.show();
//HomePrism.hide();
return app.exec();
}
示例2: IsAlreadyRunning
bool Application::IsAlreadyRunning () const
{
QLocalSocket socket;
socket.connectToServer (GetSocketName ());
if (socket.waitForConnected () ||
socket.state () == QLocalSocket::ConnectedState)
{
QDataStream out (&socket);
out << Arguments_;
if (socket.waitForBytesWritten ())
return true;
if (socket.error() == QLocalSocket::UnknownSocketError)
return true;
}
else
{
switch (socket.error ())
{
case QLocalSocket::ServerNotFoundError:
case QLocalSocket::ConnectionRefusedError:
break;
default:
qWarning () << Q_FUNC_INFO
<< "socket error"
<< socket.error ();
return true;
}
}
// Clear any halted servers and their messages
QLocalServer::removeServer (GetSocketName ());
return false;
}
示例3: listen
bool ServerCatchcopy::listen()
{
QLocalSocket socketTestConnection;
pathSocket=ExtraSocketCatchcopy::pathSocket();
socketTestConnection.connectToServer(QString::fromStdString(pathSocket));
if(socketTestConnection.waitForConnected(CATCHCOPY_COMMUNICATION_TIMEOUT))
{
error_string="Other server is listening";
emit error(error_string);
return false;
}
else
{
if(!server.removeServer(QString::fromStdString(pathSocket)))
{
error_string="Unable to remove the old server";
emit error(error_string);
}
#ifndef Q_OS_MAC
server.setSocketOptions(QLocalServer::UserAccessOption);
#endif
if(server.listen(QString::fromStdString(pathSocket)))
return true;
else
{
error_string=QStringLiteral("Unable to listen %1: %2").arg(QString::fromStdString(pathSocket)).arg(server.errorString()).toStdString();
emit error(error_string);
return false;
}
}
}
示例4: saveCommand
// Process incoming IPC command. First check if monero-wallet-gui is
// already running. If it is, send it to that instance instead, if not,
// queue the command for later use inside our QML engine. Returns true
// when queued, false if sent to another instance, at which point we can
// kill the current process.
bool IPC::saveCommand(QString cmdString){
qDebug() << QString("saveCommand called: %1").arg(cmdString);
QLocalSocket ls;
QByteArray buffer;
buffer = buffer.append(cmdString);
QString socketFilePath = this->socketFile().filePath();
ls.connectToServer(socketFilePath, QIODevice::WriteOnly);
if(ls.waitForConnected(1000)){
ls.write(buffer);
if (!ls.waitForBytesWritten(1000)){
qDebug() << QString("Could not send command \"%1\" over IPC %2: \"%3\"").arg(cmdString, socketFilePath, ls.errorString());
return false;
}
qDebug() << QString("Sent command \"%1\" over IPC \"%2\"").arg(cmdString, socketFilePath);
return false;
}
if(ls.isOpen())
ls.disconnectFromServer();
// Queue for later
this->SetQueuedCmd(cmdString);
return true;
}
示例5: initLocalConnection
void MainWidget::initLocalConnection()
{
is_running = false;
QCoreApplication::setApplicationName("localserver");
QString serverName=QCoreApplication::applicationName();
QLocalSocket socket;
socket.connectToServer(serverName);
if(socket.waitForConnected(500))
{
is_running =true;
return;
}
//连接不上服务器,就创建一个
server = new QLocalServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newLocalConnection()));
if(server->listen(serverName))
{
//防止程序崩溃时,残留进程服务,移除之
if(server->serverError() == QAbstractSocket::AddressInUseError && QFile::exists(server->serverName()))
{
QFile::remove(server->serverName());
server->listen(serverName);
}
}
}
示例6: getRunningPid
qint64 QtLocalPeer::getRunningPid() {
if (!isClient())
return 0;
QLocalSocket socket;
bool connOk = false;
for (int i = 0; i < 2; i++) {
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(5000/2);
if (connOk || i)
break;
Sleep(250);
}
if (!connOk) return -1;
const char* msg = "qbt://pid";
QDataStream ds(&socket);
ds.writeBytes(msg, qstrlen(msg));
bool res = socket.waitForBytesWritten(5000) && socket.waitForReadyRead(5000);
if (!res) return -1;
DWORD pid;
qint64 pid_size = sizeof pid;
while (socket.bytesAvailable() < pid_size)
socket.waitForReadyRead();
if (socket.read((char *)&pid, pid_size) < pid_size)
return -1;
return pid;
}
示例7: main
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//a.removeLibraryPath(a.libraryPaths().first());
qRegisterMetaType<Song>("Song");
qRegisterMetaTypeStreamOperators<Song>("Song");
MainWindow w;
QStringList args = a.arguments();
QLocalSocket socket;
socket.connectToServer("iniTunes");
QTextStream stream(&socket);
if(socket.waitForConnected(3000))
{
stream <<QString::number(PLAY)<<endl;
stream << args.at(1) <<endl;
socket.waitForBytesWritten();
exit(0);
}
else
{
qDebug()<<"Launch";
w.show();
w.createRemote();
if(args.count()==2)
{
qDebug()<<"Open";
w.open(args.at(1));
}
}
return a.exec();
}
示例8: getKeyValue
int QmKeysPrivate::getKeyValue(const struct input_event &query) {
// Try to connect to qmkeyd.
QLocalSocket socket;
socket.connectToServer(SERVER_NAME);
if (!socket.waitForConnected(1000)) {
return -1;
}
// Query for the given key
if (socket.write((char*)&query, sizeof(query)) != sizeof(query)) {
return -1;
}
if (!socket.waitForReadyRead(1000)) {
return -1;
}
struct input_event response;
int ret = 0;
// A loop because we might receive other events as well.
do {
ret = socket.read((char*)&response, sizeof(response));
if (ret == sizeof(response)) {
if (response.type == query.type && response.code == query.code) {
break;
}
}
} while (ret == sizeof(response));
socket.disconnect();
return response.value;
}
示例9: run
void LocalClient::run()
{
QLocalSocket *socket = new QLocalSocket(this);
socket->connectToServer("/tmp/testservice");
if (!socket->waitForConnected()) {
qDebug() << "could not connect to server: " << socket->errorString();
return;
}
m_client = new QJsonRpcSocket(socket, this);
QJsonRpcServiceReply *reply = m_client->invokeRemoteMethod("agent.testMethod");
connect(reply, SIGNAL(finished()), this, SLOT(processResponse()));
reply = m_client->invokeRemoteMethod("agent.testMethodWithParams", "one", false, 10);
connect(reply, SIGNAL(finished()), this, SLOT(processResponse()));
reply = m_client->invokeRemoteMethod("agent.testMethodWithVariantParams", "one", false, 10, QVariant(2.5));
connect(reply, SIGNAL(finished()), this, SLOT(processResponse()));
reply = m_client->invokeRemoteMethod("agent.testMethodWithParamsAndReturnValue", "matt");
connect(reply, SIGNAL(finished()), this, SLOT(processResponse()));
// test bulk messages
/*
QJsonRpcMessage first = QJsonRpcMessage::createRequest("agent.testMethodWithParamsAndReturnValue", "testSendMessage");
m_client->sendMessage(first);
QJsonRpcMessage second = QJsonRpcMessage::createRequest("agent.testMethodWithParamsAndReturnValue", "testSendMessages1");
QJsonRpcMessage third = QJsonRpcMessage::createRequest("agent.testMethodWithParamsAndReturnValue", "testSendMessages2");
m_client->sendMessage(QList<QJsonRpcMessage>() << second << third);
*/
}
示例10: qt_connectToServer
void qt_connectToServer()
{
if (!qt_initialized)
return;
// Determine to which server we should connect
QString server = qt_localServerName;
if (!qt_optionWidget.isEmpty())
server = qt_optionWidget;
// Check if we are already connected
if (qt_socket.serverName() == server)
return;
// Disconnect
if (qt_socket.state() == QLocalSocket::ConnectedState)
{
qt_socket.disconnectFromServer();
qt_socket.waitForDisconnected(1000);
}
// Connect to server, or local server if not available.
qt_socket.connectToServer(server);
if (!qt_socket.waitForConnected(3000))
while (qt_socket.state() != QLocalSocket::ConnectedState)
qt_socket.connectToServer(qt_localServerName);
}
示例11: QLocalSocket
bool N810GpsPlugin::sendToGpsDriverCtrl(QString cmd)
{
QLocalSocket *gpsCtrlSocket;
gpsCtrlSocket = new QLocalSocket(this);
QByteArray socketPath = ( "/var/lib/gps/gps_driver_ctrl");
gpsCtrlSocket->connectToServer(socketPath.data());
if(gpsCtrlSocket->waitForConnected()) {
qLog(Hardware)<< __PRETTY_FUNCTION__ << "connected" << cmd;
QByteArray data;
data.append(cmd);
data.append("\n");
gpsCtrlSocket->write(data);
gpsCtrlSocket->flush();
gpsCtrlSocket->disconnectFromServer();
return true;
} else {
qLog(Hardware) << __PRETTY_FUNCTION__ << "Could not connect to socket" << gpsCtrlSocket;
}
return false;
}
示例12: sendMessages
bool KNSingletonApplication::sendMessages(const QString &uniqueKey,
const QStringList &messages)
{
//Create sender client.
QLocalSocket client;
//Link to the server which is listening to the unique key.
client.connectToServer(uniqueKey, QIODevice::WriteOnly);
//If connecting failed, return false.
if(!client.waitForConnected(TimeoutLimit))
{
qDebug("Cannot connect to the local server.");
//Disconnect from the server.
client.disconnectFromServer();
return false;
}
//Generate the message data.
QByteArray messageData;
QDataStream dataWriter(&messageData, QIODevice::WriteOnly);
dataWriter << messages;
//Send the data to local server.
client.write(messageData);
//Check sending status.
if(!client.waitForBytesWritten(TimeoutLimit))
{
qDebug("Send arguments failed.");
client.disconnectFromServer();
return false;
}
//Send the arguments success.
client.disconnectFromServer();
return true;
}
示例13: main
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLocalSocket localSocket;
localSocket.connectToServer("bloggerQml", QIODevice::ReadOnly);
if(localSocket.waitForConnected(5000))
{
// there is already an application running
qDebug() << "Application is already running.";
QMessageBox::information(0, QObject::tr("Erro"), QObject::tr("A aplicação já está a ser executada."), QMessageBox::Ok);
return 0;
}
QLocalServer localServer;
localServer.listen("bloggerQml");
BloggerLoader bloggerloader;
bloggerloader.loadBlogsFromFile();
BloggerProxyModel model;
model.setSourceModel(bloggerloader.model());
Helper helper;
QtQuick2ApplicationViewer viewer;
viewer.rootContext()->setContextProperty("blogsModel", &model);
viewer.rootContext()->setContextProperty("helper", &helper);
viewer.rootContext()->setContextProperty("bloggerloader", &bloggerloader);
viewer.setMainQmlFile(QStringLiteral("qml/blogerQML/main.qml"));
viewer.showExpanded();
int res = app.exec();
bloggerloader.saveDB();
return res;
}
示例14: hasPrevious
bool SingleInstance::hasPrevious(const QString &name, const QStringList &args)
{
qDebug() << "Checking for previous instance...";
QLocalSocket socket;
socket.connectToServer(name, QLocalSocket::ReadWrite);
if (socket.waitForConnected())
{
qDebug() << "Connection found!";
qDebug() << "Forwarding argument to existing instance...";
QByteArray buffer;
for (auto item : args)
{
buffer.append(item+"\n");
}
qDebug() << "Forwading buffer=" << buffer;
socket.write(buffer);
return true;
}
qDebug() << socket.errorString();
qDebug() << "No connection found";
return false;
}
示例15: sendMessage
bool QtLocalPeer::sendMessage(const QString &message, int timeout)
{
if (!isClient())
return false;
QLocalSocket socket;
bool connOk = false;
for (int i = 0; i < 2; i++) {
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2);
if (connOk || i)
break;
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
if (!connOk)
return false;
QByteArray uMsg(message.toUtf8());
QDataStream ds(&socket);
ds.writeBytes(uMsg.constData(), uMsg.size());
bool res = socket.waitForBytesWritten(timeout);
res &= socket.waitForReadyRead(timeout); // wait for ack
res &= (socket.read(qstrlen(ack)) == ack);
return res;
}