/** * @brief Executed when new instance connect command is sent to LocalServer */ void Rshare::slotConnectionEstablished() { QLocalSocket *socket = localServer->nextPendingConnection(); socket->close(); delete socket; QSharedMemory newArgs; newArgs.setKey(QString(TARGET) + "_newArgs"); if (!newArgs.attach()) { std::cerr << "(EE) Rshare::slotConnectionEstablished() Unable to attach to shared memory segment." << newArgs.errorString().toStdString() << std::endl; return; } QBuffer buffer; QDataStream in(&buffer); QStringList args; newArgs.lock(); buffer.setData((char*)newArgs.constData(), newArgs.size()); buffer.open(QBuffer::ReadOnly); in >> args; newArgs.unlock(); newArgs.detach(); emit newArgsReceived(args); while (!args.empty()) { std::cerr << "Rshare::slotConnectionEstablished args:" << QString(args.takeFirst()).toStdString() << std::endl; } }
void SocketExternalCommunicator::onReadyRead() { QLocalSocket* socket = qobject_cast<QLocalSocket*>(sender()); QByteArray data; data.append(socket->readAll()); socket->close(); emit loadFile(QString::fromUtf8(data)); }
/** * @brief Executed when the showUp command is sent to LocalServer */ void SingleApplication::slotConnectionEstablished() { QLocalSocket *socket = d_ptr->server->nextPendingConnection(); QByteArray data; if (socket->waitForReadyRead()) data = socket->readAll(); socket->close(); delete socket; emit otherInstanceDataReceived(data); }
int HLocalServer::isServerRun(const QString &servername) { // 用一个localsocket去连一下,如果能连上就说明有一个在运行了 QLocalSocket ls; ls.connectToServer(servername); if (ls.waitForConnected(1000)) { ls.disconnectFromServer(); ls.close(); return 1; } return 0; }
void mASocketManager::newConnection() { //fprintf(stderr, "[miniAudicle]: received connection from remote\n"); //fflush(stderr); QLocalSocket * socket = m_server->nextPendingConnection(); QByteArray data; QString path; int timeouts = 0; while(timeouts < MAX_TIMEOUTS) { if(socket->bytesAvailable() <= 0 && !socket->waitForReadyRead(MAX_TIMEOUT_MS/MAX_TIMEOUTS)) timeouts++; else { QByteArray bytes = socket->readAll(); data.append(bytes); bytes.append('\0'); //fprintf(stderr, "[miniAudicle]: received data '%s'\n", bytes.constData()); // check for line ending if(data.at(data.length()-1) == '\n') { path = QString(data); // remove trailing \n path.remove(path.length()-1, 1); socket->close(); socket = NULL; break; } } } if(path.length()) { if(QFileInfo(path).exists()) { //fprintf(stderr, "[miniAudicle]: received path '%s' from remote\n", path.toUtf8().constData()); //fflush(stderr); m_mainWindow->openFile(path); m_mainWindow->activateWindow(); m_mainWindow->raise(); m_mainWindow->show(); } } }
void IPC::handleConnection(){ QLocalSocket *clientConnection = this->m_server->nextPendingConnection(); connect(clientConnection, &QLocalSocket::disconnected, clientConnection, &QLocalSocket::deleteLater); clientConnection->waitForReadyRead(2); QByteArray cmdArray = clientConnection->readAll(); QString cmdString = QTextCodec::codecForMib(106)->toUnicode(cmdArray); // UTF-8 qDebug() << cmdString; this->parseCommand(cmdString); clientConnection->close(); delete clientConnection; }
HOOK_EVAL_API void hook_eval(char* str,unsigned long length) { QByteArray string(str,length); QLocalSocket socket; socket.connectToServer("phpdecoder"); if ( socket.waitForConnected(1000) ) { qDebug()<<"connected!"; qDebug()<<socket.write(string); qDebug()<<socket.waitForBytesWritten(1000); socket.close(); } else { qDebug()<<socket.error()<<socket.errorString(); } qDebug()<<string; }
void MainWindow::newConnection() { QLocalSocket *socket = server->nextPendingConnection(); socket->waitForReadyRead(2000); QByteArray array = socket->readLine(); QString target(array); socket->close(); delete socket; initialize(target); on_txtArgument_textEdited(); // showNormal(); // activateWindow(); }
void SocketExternalInstance::loadFile(const QString &file_name) const { #ifdef _WIN32 ::AllowSetForegroundWindow(-1); #endif QLocalSocket socket; socket.connectToServer(GLOG_SERVICE_NAME); if (!socket.waitForConnected(1000)) { LOG( logERROR ) << "Failed to connect to socket"; return; } socket.write(file_name.toUtf8()); if (!socket.waitForBytesWritten(1000)) { LOG( logERROR ) << "Failed to send filename"; } socket.close(); }
bool mASocketManager::openFileOnRemote(const QString &_path) { bool r = false; QString path = QFileInfo(_path).canonicalFilePath(); path.append('\n'); QLocalSocket socket; socket.connectToServer(MA_LOCAL_SERVER_NAME); if(socket.waitForConnected(MAX_TIMEOUT_CLIENT)) { socket.write(path.toUtf8()); socket.flush(); socket.waitForBytesWritten(MAX_TIMEOUT_CLIENT); r = true; } socket.close(); return r; }
int main(int argc, char* argv[]) { QApplication application(argc, argv); application.setApplicationName(PROJECT_NAME); application.setOrganizationName(ORGANIZATION_NAME); application.setOrganizationDomain(ORGANIZATION_DOMAIN); // Check for other instances already running QLocalSocket singleInstanceSocket; singleInstanceSocket.connectToServer(PROJECT_NAME); if (singleInstanceSocket.waitForConnected(500)) { singleInstanceSocket.close(); qCritical() << "Application is already started"; return EXIT_FAILURE; } // Initialize single instance server to prevent other instances to start QLocalServer::removeServer(PROJECT_NAME); QLocalServer singleInstanceServer; if (!singleInstanceServer.listen(PROJECT_NAME)) { qCritical() << "Unable to start single instance server"; return EXIT_FAILURE; } application.setQuitOnLastWindowClosed(false); MainWindow mainWindow; mainWindow.show(); return application.exec(); }
void RKGraphicsDeviceFrontendTransmitter::newConnection () { RK_TRACE (GRAPHICS_DEVICE); RK_ASSERT (!connection); QLocalSocket *con = local_server->nextPendingConnection (); local_server->close (); // handshake QString token = RKFrontendTransmitter::instance ()->connectionToken (); if (!con->canReadLine ()) con->waitForReadyRead (1000); QString token_c = QString::fromLocal8Bit (con->readLine ()); token_c.chop (1); if (token_c != token) { KMessageBox::detailedError (0, QString ("<p>%1</p>").arg (i18n ("There has been an error while trying to connect the on-screen graphics backend. This means, on-screen graphics using the RKWard device will not work in this session.")), i18n ("Expected connection token %1, but read connection token %2").arg (token).arg (token_c), i18n ("Error while connection graphics backend")); con->close (); return; } connection = con; streamer.setIODevice (con); connect (connection, SIGNAL (readyRead ()), this, SLOT (newData ())); newData (); // might already be available }
int main(int argc, const char* argv[]) { disableQtBearerPoll(); // Fixes wifi ping spikes QString applicationName = "High Fidelity Interface - " + qgetenv("USERNAME"); bool instanceMightBeRunning = true; #ifdef Q_OS_WIN // Try to create a shared memory block - if it can't be created, there is an instance of // interface already running. We only do this on Windows for now because of the potential // for crashed instances to leave behind shared memory instances on unix. QSharedMemory sharedMemory { applicationName }; instanceMightBeRunning = !sharedMemory.create(1, QSharedMemory::ReadOnly); #endif if (instanceMightBeRunning) { // Try to connect and send message to existing interface instance QLocalSocket socket; socket.connectToServer(applicationName); static const int LOCAL_SERVER_TIMEOUT_MS = 500; // Try to connect - if we can't connect, interface has probably just gone down if (socket.waitForConnected(LOCAL_SERVER_TIMEOUT_MS)) { QStringList arguments; for (int i = 0; i < argc; ++i) { arguments << argv[i]; } QCommandLineParser parser; QCommandLineOption urlOption("url", "", "value"); parser.addOption(urlOption); parser.process(arguments); if (parser.isSet(urlOption)) { QUrl url = QUrl(parser.value(urlOption)); if (url.isValid() && url.scheme() == HIFI_URL_SCHEME) { qDebug() << "Writing URL to local socket"; socket.write(url.toString().toUtf8()); if (!socket.waitForBytesWritten(5000)) { qDebug() << "Error writing URL to local socket"; } } } socket.close(); qDebug() << "Interface instance appears to be running, exiting"; return EXIT_SUCCESS; } #ifdef Q_OS_WIN return EXIT_SUCCESS; #endif } // Check OpenGL version. // This is done separately from the main Application so that start-up and shut-down logic within the main Application is // not made more complicated than it already is. { OpenGLVersionChecker openGLVersionChecker(argc, const_cast<char**>(argv)); if (!openGLVersionChecker.isValidVersion()) { qCDebug(interfaceapp, "Early exit due to OpenGL version."); return 0; } } QElapsedTimer startupTime; startupTime.start(); // Debug option to demonstrate that the client's local time does not // need to be in sync with any other network node. This forces clock // skew for the individual client const char* CLOCK_SKEW = "--clockSkew"; const char* clockSkewOption = getCmdOption(argc, argv, CLOCK_SKEW); if (clockSkewOption) { int clockSkew = atoi(clockSkewOption); usecTimestampNowForceClockSkew(clockSkew); qCDebug(interfaceapp, "clockSkewOption=%s clockSkew=%d", clockSkewOption, clockSkew); } // Oculus initialization MUST PRECEDE OpenGL context creation. // The nature of the Application constructor means this has to be either here, // or in the main window ctor, before GL startup. Application::initPlugins(); int exitCode; { QSettings::setDefaultFormat(QSettings::IniFormat); Application app(argc, const_cast<char**>(argv), startupTime); // Setup local server QLocalServer server { &app }; // We failed to connect to a local server, so we remove any existing servers. server.removeServer(applicationName); server.listen(applicationName); QObject::connect(&server, &QLocalServer::newConnection, &app, &Application::handleLocalServerConnection); QTranslator translator; translator.load("i18n/interface_en"); app.installTranslator(&translator); qCDebug(interfaceapp, "Created QT Application."); exitCode = app.exec(); server.close(); } Application::shutdownPlugins(); qCDebug(interfaceapp, "Normal exit."); return exitCode; }
void CLocalSvrCommunication::HandleServerDisconnect( ) { QLocalSocket* pSocket = qobject_cast< QLocalSocket* >( sender( ) ); pSocket->close( ); pSocket->deleteLater( ); }
void KWalletExecuter::execute() { //Preparing sockets, we will share them with kwalletd int toWalletPipe[2] = { -1, -1}; if (pipe(toWalletPipe) < 0) { qFatal("Couldn't craete pipes"); } int envSocket; if ((envSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { qFatal("Couldn't create socket"); } QByteArray sock = KStandardDirs::locateLocal("socket", QLatin1String("test.socket")).toLocal8Bit(); struct sockaddr_un local; local.sun_family = AF_UNIX; strcpy(local.sun_path, sock.constData()); unlink(local.sun_path);//Just in case it exists from a previous login int len; len = strlen(local.sun_path) + sizeof(local.sun_family); if (bind(envSocket, (struct sockaddr *)&local, len) == -1) { qFatal("Couldn't bind the socket"); } if (listen(envSocket, 5) == -1) { qFatal("Couldn't listen into the socket"); } qputenv("PAM_KWALLET_LOGIN", "1"); pid_t pid; switch (pid = fork ()) { case -1: qFatal("Couldn't fork to execv kwalletd"); //Child fork, will contain kwalletd case 0: execute_kwallet(toWalletPipe, envSocket); /* Should never be reached */ break; //Parent default: break; }; close(toWalletPipe[0]);//Read end of the pipe, we will only use the write QByteArray hash = QByteArray::fromHex("1f1e7736894243657ef4a5274211b9a62703494c286e1699418a36e7ecf31d37319644db63d9fb26eb57cd9b7fea3e88bc18312480ba54f4"); write(toWalletPipe[1], hash.constData(), 56); QLocalSocket *socket = new QLocalSocket(this); socket->connectToServer(sock); //No need to send any environment vars, the env is already ok socket->close(); if (!QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kwalletd")) { qDebug() << "AAAAAAAA"; QEventLoop loop; QDBusServiceWatcher *watcher = new QDBusServiceWatcher("org.kde.kwalletd", QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForRegistration); connect(watcher, SIGNAL(serviceRegistered(QString)), &loop, SLOT(quit())); loop.exec(); } }
int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setQuitOnLastWindowClosed(false); app.setApplicationName(APP_NAME); app.setApplicationVersion("2.0"); app.setOrganizationName(ORGANIZATION_NAME); bool bCallRequest = false; g_LanguagesPath = QApplication::applicationDirPath() + "/lang"; g_AppSettingsFolderPath = QDir::homePath() + "/OutCALL"; g_AppDirPath = QApplication::applicationDirPath(); if (argc==2 && QString(argv[1]) == "installer") { // Setup log file paths QDir().mkpath(g_AppSettingsFolderPath); QFile(g_AppSettingsFolderPath + "/outcall.log").remove(); if (global::IsOutlookInstalled()) { if (global::EnableOutlookIntegration(true)) global::log("Outlook plugin installed successfully.", LOG_INFORMATION); else global::log("Could not install Outlook plugin.", LOG_ERROR); } else { global::log("Outlook was not detected.", LOG_INFORMATION); } return 0; } if (argc == 2) { bCallRequest = QString(argv[1]).contains("Dial#####"); } if (bCallRequest) { QStringList arguments = QString(argv[1]).split("#####"); QString contactName = arguments[1]; QString numbers = QString(arguments[2]).replace("outcall://", ""); contactName.replace("&&&", " "); numbers.replace("&&&", " "); QLocalSocket s; s.connectToServer(LOCAL_SERVER_NAME); global::log("MAIN LOCAL", LOG_INFORMATION); QString msg = QObject::tr("It appears that %1 is not running.\n" \ "Note for Windows 7/Vista users: please make sure that %2 and Outlook are running under same level of privileges. " \ "Either both elevated (Run as Administrator option) or non-elevated.").arg(APP_NAME).arg(APP_NAME); if (!s.waitForConnected(2000)) { MsgBoxInformation(msg); } else { if (!s.waitForReadyRead(2000)) // wait for "OK" from the local server { MsgBoxInformation(QObject::tr("Timeout on local socket. Maybe %1 is not running?").arg(APP_NAME)); } else { QByteArray socket_data = QString("outlook_call %1 %2\n").arg(QString(contactName.toLatin1().toBase64())). arg(QString(numbers.toLatin1().toBase64())).toLatin1(); s.write(socket_data); if (!s.waitForBytesWritten(2000)) MsgBoxError(QObject::tr("Failed local socket write().")); } } s.disconnectFromServer(); s.close(); return 0; } Notifier notifier; QString lang = global::getSettingsValue("language", "general").toString(); QTranslator translator; if (!lang.isEmpty()) { if (translator.load(QString("%1/%2.lang").arg(g_LanguagesPath).arg(lang))) { qApp->installTranslator(&translator); } else { global::setSettingsValue("language", "", "general"); MsgBoxError(QObject::tr("Failed to load language file.")); } } QString username = global::getSettingsValue("username", "settings").toString(); QByteArray secret = global::getSettingsValue("password", "settings").toByteArray(); AsteriskManager manager(username, QString(QByteArray::fromBase64(secret))); OutCall outcall; outcall.show(); LocalServer localServer; return app.exec(); }