Ejemplo n.º 1
0
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;
}
Ejemplo n.º 2
0
    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;
    }
Ejemplo n.º 3
0
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;
}
RKGraphicsDeviceBackendTransmitter* RKGraphicsDeviceBackendTransmitter::instance () {
	if (_instance) return _instance;
	RK_TRACE (GRAPHICS_DEVICE);

	QLocalSocket *con = new QLocalSocket ();
	con->connectToServer (RKRBackendProtocolBackend::rkdServerName ());
	con->waitForConnected (2000);
	if (con->state () == QLocalSocket::ConnectedState) {
		con->write (RKRBackendTransmitter::instance ()->connectionToken ().toLocal8Bit ().data ());
		con->write ("\n");
		con->waitForBytesWritten (1000);
		_instance = new RKGraphicsDeviceBackendTransmitter (con, true);
		return _instance;
	}
	return 0;
}
Ejemplo n.º 5
0
int main(void)
{
    QLocalSocket socket;
    socket.connectToServer(SOCK_PATH);
    socket.open(QIODevice::ReadWrite);

    printf("Connected.\n");
    char str[100];
    while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
        if (socket.write(str, strlen(str)) == -1) {
            perror("send");
            return EXIT_FAILURE;
        }

        int t;
        if ((t = socket.read(str, 100)) > 0) {
            str[t] = '\0';
            printf("echo> %s", str);
        } else {
            if (t < 0)
                perror("recv");
            else
                printf("Server closed connection.\n");
            return EXIT_FAILURE;
        }
    }

    return EXIT_SUCCESS;
}
Ejemplo n.º 6
0
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;
}
Ejemplo n.º 7
0
void sendData(QLocalSocket& sock, int num) {
  qDebug("send %d", num);
  QByteArray block;
  QDataStream ds(&block, QIODevice::WriteOnly);
  ds << num;
  sock.write(block);
}
Ejemplo n.º 8
0
// 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;
}
Ejemplo n.º 9
0
void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    while (socket->bytesAvailable() < (int)sizeof(quint32))
        socket->waitForReadyRead();
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    if (got < 0) {
        qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
        delete socket;
        return;
    }
    QString message(QString::fromUtf8(uMsg));
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    delete socket;
    emit messageReceived(message); //### (might take a long time to return)
}
Ejemplo n.º 10
0
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
    bool fResult = false;
    for (const QString& r : savedPaymentRequests)
    {
        QLocalSocket* socket = new QLocalSocket();
        socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
        if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
        {
            delete socket;
            socket = nullptr;
            return false;
        }

        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_0);
        out << r;
        out.device()->seek(0);

        socket->write(block);
        socket->flush();
        socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
        socket->disconnectFromServer();

        delete socket;
        socket = nullptr;
        fResult = true;
    }

    return fResult;
}
Ejemplo n.º 11
0
void pqdbg_send_message(int lvl, const QString &msg, const QString &title)
{
#ifdef PQDEBUG
    static QMutex mutex;

    mutex.lock();
    QLocalSocket *debugSocket = PHPQt5::debugSocket();

    if(debugSocket->isOpen()) {
        /*
        QByteArray data;

        QDataStream out(&data, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_0);
        out << reinterpret_cast<quint64>(PQEngine::pqeEngine);
        out << PQEngine::pqeCoreName;
        out << lvl;
        out << title;
        out << msg;
        out.device()->reset();

//        = QString("%1:::%2:::%3:::%4:::%5:::%")
//                .arg(reinterpret_cast<quint64>(PQEngine::pqeEngine))
//                .arg(PQEngine::pqeCoreName)
//                .arg(lvl)
//                .arg(title)
//                .arg(msg).toUtf8();

        debugSocket->write(data);
        debugSocket->waitForBytesWritten();
        */

        QString str = QString("%1:::%2:::%3:::%4:::%5:::%6:::%")
                        .arg(reinterpret_cast<quint64>(PQEngine::pqeEngine))
                        .arg(PQEngine::pqeCoreName)
                        .arg(reinterpret_cast<quint64>(QThread::currentThread()))
                        .arg(lvl)
                        .arg(title)
                        .arg(msg).toUtf8();

        /*
        QByteArray block;
        QDataStream sendStream(&block, QIODevice::ReadWrite);
        sendStream << quint16(0) << str;
        sendStream.device()->seek(0);
        sendStream << (quint16)(block.size() - sizeof(quint16));
        */

        debugSocket->write(str.toUtf8());
        debugSocket->waitForBytesWritten();
    }

    mutex.unlock();
#else
    Q_UNUSED(lvl);
    Q_UNUSED(msg);
    Q_UNUSED(title);
#endif
}
Ejemplo n.º 12
0
void ControlPeer::receiveConnection()
{
    QLocalSocket* socket = p->server->nextPendingConnection();
    if (!socket) {
        return;
    }

    while (socket->bytesAvailable() < (int)sizeof(quint32)) {
        socket->waitForReadyRead();
    }

    QDataStream ds(socket);
    QByteArray uMsg;    
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));

    if (got < 0) {
        qWarning("Guzum.ControlPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
        delete socket;
        return;
    }

    QString message(QString::fromUtf8(uMsg));
    socket->write(ACK, qstrlen(ACK));
    socket->waitForBytesWritten(1000);
    delete socket;

    // split message into the tokens, the format is the following:
    // <method_name>\n<arg0>\n<arg1> etc
    QStringList tokens = message.split("\n");
    QString methodName = tokens[0];

    if (methodName == SHOW_DIALOG_METHOD) {
        showFileSelectorDialog();
    } else if (methodName == OPEN_FILE_METHOD) {
        if (tokens.size() == 2) {
            // just open file using default gnupg home
            QString filename = tokens[1];
            editFile(filename);
        } else if (tokens.size() == 3) {
            // use file and custom gnupg home
            QString filename = tokens[1];
            QString gnupgHome = tokens[2];
            editFile(filename, gnupgHome);
        }
        
        QString filename = message.mid(qstrlen(OPEN_FILE_METHOD)+1);
    }
}
Ejemplo n.º 13
0
void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    while (socket->bytesAvailable() < (int)sizeof(quint32))
        socket->waitForReadyRead();
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    QString message(QString::fromUtf8(uMsg));
#ifdef Q_OS_WIN
    if (message == "qbt://pid") {
      qint64 pid = GetCurrentProcessId();
      socket->write((const char *)&pid, sizeof pid);
    } else {
      socket->write(ack, qstrlen(ack));
    }
#else
    socket->write(ack, qstrlen(ack));
#endif
    socket->waitForBytesWritten(1000);
    delete socket;
#ifdef Q_OS_WIN
    if (message == "qbt://pid")
      return;
#endif
    emit messageReceived(message); //### (might take a long time to return)
}
Ejemplo n.º 14
0
bool QtLocalPeer::serverSendMessage(const QString &message, int client_id, int timeout)
{
    qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<client_id;
    QLocalSocket *socket = NULL;

    QHash<QLocalSocket*, int>::iterator it;

    if (client_id == -1) {
        // broadcast
        for (it = this->clients.begin(); it != this->clients.end(); it++) {
            socket = it.key();
            
            // QByteArray uMsg(message.toUtf8());
            // QDataStream ds(socket);
            // ds.writeBytes(uMsg.constData(), uMsg.size());
            socket->write(message.toAscii());
            bool res = socket->waitForBytesWritten(timeout);
        }
    } else {
        for (it = this->clients.begin(); it != this->clients.end(); it++) {
            if (it.value() == client_id) {
                socket = it.key();
            }
        }

        if (socket) {
            // qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<client_id;
            // QByteArray uMsg(message.toUtf8());
            // QDataStream ds(socket);
            // ds.writeBytes(uMsg.constData(), uMsg.size());
            socket->write(message.toAscii());
            bool res = socket->waitForBytesWritten(timeout);
        } else {
            qDebug()<<"can not find socket for client:"<<client_id;
        }
    }

    return true;
}
Ejemplo n.º 15
0
static bool sendData(const QByteArray &out, QByteArray *in)
{
#if USE_LOCAL_SOCKETS
    QLocalSocket socket;
    socket.connectToServer("gdrdeamon");
#else
    QTcpSocket socket;
    socket.connectToHost("127.0.0.1", 15001);
#endif
    if (!socket.waitForConnected(1000))
        return false;

    qint32 size = out.size();
    socket.write((char*)&size, sizeof(qint32));
    socket.write(out);
    while (socket.bytesToWrite() && socket.waitForBytesWritten())
        ;

    while (socket.waitForReadyRead())
        in->append(socket.readAll());

    return true;
}
Ejemplo n.º 16
0
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;
}
Ejemplo n.º 17
0
void SocketHandler::newConnection()
{
    sensordLogT() << "[SocketHandler]: New connection received.";

    while (m_server->hasPendingConnections()) {

        QLocalSocket* socket = m_server->nextPendingConnection();
        connect(socket, SIGNAL(readyRead()), this, SLOT(socketReadable()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
        connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError)));

        // Initialize socket
        socket->write("\n", 1);
        socket->waitForBytesWritten();
    }
}
Ejemplo n.º 18
0
void YACReaderLocalServer::sendResponse()
{
	/*QLocalSocket *clientConnection = localServer->nextPendingConnection();

    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    QDataStream in(clientConnection);
    in.setVersion(QDataStream::Qt_4_0);

    if (clientConnection->bytesAvailable() == 0)
		return;
 
    if (in.atEnd())
        return;

    QString message;
    in >> message;

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << QString("OK");

    clientConnection->write(block);
    clientConnection->flush();
    clientConnection->disconnectFromServer();*/

	     QByteArray block;
     QDataStream out(&block, QIODevice::WriteOnly);
     out.setVersion(QDataStream::Qt_4_0);
     out << (quint16)0;
     out << QString("ok");
     out.device()->seek(0);
     out << (quint16)(block.size() - sizeof(quint16));

     QLocalSocket *clientConnection = localServer->nextPendingConnection();
     connect(clientConnection, SIGNAL(disconnected()),
             clientConnection, SLOT(deleteLater()));

     clientConnection->write(block);
     clientConnection->flush();
     clientConnection->disconnectFromServer();

}
Ejemplo n.º 19
0
void Server::sendFortune()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint16)0;
    out << fortunes.at(qrand() % fortunes.size());
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    QLocalSocket *clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->flush();
    clientConnection->disconnectFromServer();
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{

#if QT_NO_DEBUG
    QLocalSocket socket;
    socket.connectToServer(SERVER);
    if(socket.waitForConnected(1000))
    {
        if (argc == 2)
        {

            socket.write(argv[1]);
            socket.flush();
            socket.waitForBytesWritten();

        }
        socket.disconnectFromServer();

        exit(0);
    }
    else
    {
        if (argc != 1)
            exit(0);

    }
#endif

    QApplication a(argc, argv);
    MainWindow w;





    QTranslator translator ;
    translator.load("/usr/share/qt/translations/qt_cs");
    a.installTranslator(&translator);

    //w.show();
    
    return a.exec();

}
Ejemplo n.º 21
0
bool Application::sendRaiseRequest()
{
    if (!d_ptr->isRunning)
        return false;

    QLocalSocket localSocket;
    localSocket.connectToServer(GUI_APPLICATION_SHARED_MEMORY_KEY, QIODevice::WriteOnly);

    if (!localSocket.waitForConnected(GUI_APPLICATION_LOCAL_SOCKET_TIMEOUT))
        return false;

    localSocket.write(QString("raise").toUtf8());

    if (!localSocket.waitForBytesWritten(GUI_APPLICATION_LOCAL_SOCKET_TIMEOUT))
        return false;

    localSocket.disconnectFromServer();
    return true;
}
Ejemplo n.º 22
0
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();
}
Ejemplo n.º 23
0
void qt_flushOutBuffer()
{
	if (!qt_initialized)
		return;

	// Write the block size at the beginning of the bock
	QDataStream sizeStream(&qt_socket);
	sizeStream << (quint32)(qt_outBuffer.size());
	// Write the block to the QLocalSocket
	qt_socket.write(qt_outBuffer);
	// waitForBytesWritten(-1) is supposed implement this loop, but it does not seem to work !
	// update: seems to work with Qt 4.5
	while (qt_socket.bytesToWrite() > 0)
	{
		qt_socket.flush();
		qt_socket.waitForBytesWritten(-1);
	}
	// Reset the buffer
	qt_out.device()->seek(0);
	qt_outBuffer.clear();
}
Ejemplo n.º 24
0
size_t callback_read_file(void *ptr, size_t size, size_t nmemb, void *userp)
{
    // qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<size<<nmemb<<userp;

    size_t tlen = size * nmemb, rlen = 0;
    QBuffer strbuf;
    QByteArray line;
    int n = 0, wlen = 0;

    CurlFtp *ftp = static_cast<CurlFtp*>(userp);
    QLocalSocket *router = ftp->getDataSock2();

    strbuf.setData((const char*)ptr, tlen);
    strbuf.open(QBuffer::ReadOnly);
    // Q_ASSERT(strbuf.canReadLine()); //  ???
    rlen = 0;
    while (!strbuf.atEnd()) {
        if (strbuf.canReadLine()) {
            line = strbuf.readLine();
        } else {
            line = strbuf.readAll();
        }
        rlen += line.length();
        wlen = router->write(line);
        // qDebug()<<"Line: "<<n++<<line.length()<<wlen;
        // fprintf(stdout, "%s", ".");
        // fflush(stdout);
        Q_ASSERT(line.length() == wlen);
        // break;
    }
    strbuf.close();
    router->flush();

    // qDebug()<<"can rw:"<<router->isReadable()<<router->isWritable()<<router->isOpen();
    // fprintf(stdout, "route read file:. %p %d %s", router, router->bytesAvailable(), "\n");
    fflush(stdout);

    return rlen;
    return 0;
}
Ejemplo n.º 25
0
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;
}
Ejemplo n.º 26
0
bool QtLocalPeer::clientSendMessage(const QString &message, int timeout)
{
    QLocalSocket *socket = new QLocalSocket();
    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) {
        delete socket;
        return false;
    }

    int client_id = this->client_seq ++;
    this->clients.insert(socket, client_id);
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));

    // QByteArray uMsg(message.toUtf8());
    // QDataStream ds(socket);
    // ds.writeBytes(uMsg.constData(), uMsg.size());
    socket->write(message.toAscii());
    bool res = socket->waitForBytesWritten(timeout);
    // res &= socket.waitForReadyRead(timeout);   // wait for ack
    // res &= (socket.read(qstrlen(ack)) == ack);
    // qDebug()<<"client send msg:"<<message<<res;
    return res;
    return true;
}
Ejemplo n.º 27
0
void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    int client_id = this->client_seq ++;
    this->clients.insert(socket, client_id);
    QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
    QObject::connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));

    return; 
    // multi client long connection support
    while (socket->bytesAvailable() < (int)sizeof(quint32))
        socket->waitForReadyRead();
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    QString message(QString::fromUtf8(uMsg));
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    // delete socket;
    emit messageReceived(message); //### (might take a long time to return)
}
Ejemplo n.º 28
0
void QtLocalPeer::receiveConnection()
{
    QLocalSocket* socket = server->nextPendingConnection();
    if (!socket)
        return;

    // Why doesn't Qt have a blocking stream that takes care of this shait???
    while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {
        if (!socket->isValid()) // stale request
            return;
        socket->waitForReadyRead(1000);
    }
    QDataStream ds(socket);
    QByteArray uMsg;
    quint32 remaining;
    ds >> remaining;
    uMsg.resize(remaining);
    int got = 0;
    char* uMsgBuf = uMsg.data();
    //qDebug() << "RCV: remaining" << remaining;
    do {
        got = ds.readRawData(uMsgBuf, remaining);
        remaining -= got;
        uMsgBuf += got;
        //qDebug() << "RCV: got" << got << "remaining" << remaining;
    } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
    //### error check: got<0
    if (got < 0) {
        qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
        delete socket;
        return;
    }
    // ### async this
    QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
    socket->write(ack, qstrlen(ack));
    socket->waitForBytesWritten(1000);
    emit messageReceived(message, socket); // ##(might take a long time to return)
}
Ejemplo n.º 29
0
bool Application::IsAlreadyRunning () const
{
	QLocalSocket socket;
	socket.connectToServer (GetSocketName ());
	if (socket.waitForConnected () ||
			socket.state () == QLocalSocket::ConnectedState)
	{
		QByteArray toSend;
		{
			QDataStream out (&toSend, QIODevice::WriteOnly);
			out << Arguments_;
		}
		socket.write (toSend);
		socket.disconnectFromServer ();
		socket.waitForDisconnected ();
		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;
}
Ejemplo n.º 30
0
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;
}