Example #1
0
//----------------------------------------------------------------------------------
void tst_QTcpServer::ipv4LoopbackPerformanceTest()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy)
        return;

    QTcpServer server;
    QVERIFY(server.listen(QHostAddress::LocalHost));

    QVERIFY(server.isListening());

    QTcpSocket clientA;
    clientA.connectToHost(QHostAddress::LocalHost, server.serverPort());
    QVERIFY(clientA.waitForConnected(5000));
    QVERIFY(clientA.state() == QAbstractSocket::ConnectedState);

    QVERIFY(server.waitForNewConnection());
    QTcpSocket *clientB = server.nextPendingConnection();
    QVERIFY(clientB);

    QByteArray buffer(16384, '@');
    QTime stopWatch;
    stopWatch.start();
    qlonglong totalWritten = 0;
    while (stopWatch.elapsed() < 5000) {
        QVERIFY(clientA.write(buffer.data(), buffer.size()) > 0);
        clientA.flush();
        totalWritten += buffer.size();
        while (clientB->waitForReadyRead(100)) {
            if (clientB->bytesAvailable() == 16384)
                break;
        }
        clientB->read(buffer.data(), buffer.size());
        clientB->write(buffer.data(), buffer.size());
        clientB->flush();
        totalWritten += buffer.size();
        while (clientA.waitForReadyRead(100)) {
            if (clientA.bytesAvailable() == 16384)
                break;
        }
        clientA.read(buffer.data(), buffer.size());
    }

    qDebug("\t\t%s: %.1fMB/%.1fs: %.1fMB/s",
           server.serverAddress().toString().toLatin1().constData(),
           totalWritten / (1024.0 * 1024.0),
           stopWatch.elapsed() / 1000.0,
           (totalWritten / (stopWatch.elapsed() / 1000.0)) / (1024 * 1024));

    delete clientB;
}
Example #2
0
//----------------------------------------------------------------------------------
void tst_QTcpServer::ipv4PerformanceTest()
{
    QTcpSocket probeSocket;
    probeSocket.connectToHost(QtNetworkSettings::serverName(), 143);
    QVERIFY(probeSocket.waitForConnected(5000));

    QTcpServer server;
    QVERIFY(server.listen(probeSocket.localAddress(), 0));

    QTcpSocket clientA;
    clientA.connectToHost(server.serverAddress(), server.serverPort());
    QVERIFY(clientA.waitForConnected(5000));

    QVERIFY(server.waitForNewConnection(5000));
    QTcpSocket *clientB = server.nextPendingConnection();
    QVERIFY(clientB);

    QByteArray buffer(16384, '@');
    QTime stopWatch;
    stopWatch.start();
    qlonglong totalWritten = 0;
    while (stopWatch.elapsed() < 5000) {
        qlonglong writtenA = clientA.write(buffer.data(), buffer.size());
        clientA.flush();
        totalWritten += buffer.size();
        while (clientB->waitForReadyRead(100)) {
            if (clientB->bytesAvailable() == writtenA)
                break;
        }
        clientB->read(buffer.data(), buffer.size());
        qlonglong writtenB = clientB->write(buffer.data(), buffer.size());
        clientB->flush();
        totalWritten += buffer.size();
        while (clientA.waitForReadyRead(100)) {
            if (clientA.bytesAvailable() == writtenB)
               break;
        }
        clientA.read(buffer.data(), buffer.size());
    }

    qDebug("\t\t%s: %.1fMB/%.1fs: %.1fMB/s",
           probeSocket.localAddress().toString().toLatin1().constData(),
           totalWritten / (1024.0 * 1024.0),
           stopWatch.elapsed() / 1000.0,
           (totalWritten / (stopWatch.elapsed() / 1000.0)) / (1024 * 1024));

    delete clientB;
}
void lsLogServitemThreated::run()
{
    QTcpSocket tcpSocket;

    if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
        emit error(tcpSocket.error());
        return;
    }

    while ( tcpSocket.isOpen() )
    {
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_0);
        out << (quint16)0;
        out << text;
        text.clear();
        out.device()->seek(0);
        out << (quint16)(block.size() - sizeof(quint16));

        tcpSocket.write(block);
        tcpSocket.flush();

        while ( tcpSocket.isOpen() && text.isEmpty() )
        {
            msleep(100);
        }
    }

    tcpSocket.disconnectFromHost();
    tcpSocket.waitForDisconnected();
}
Example #4
0
File: server.cpp Project: otri/vive
/* perform the operations for a frame:
 *   - check to see if the connections are still alive (checkAlive)
 *      - this will emit connectionsChanged if there is a any change in the connection status
 *   - grab a text stream of the current model data ( stream << *subjectList )
 *   - put the text stream on the wire s->write(...)
*/
void MyServer::process()
{
    stopProfile("Other");

    working = true;

    startProfile("checkAlive");
    int alive = checkAlive();
    stopProfile("checkAlive");

    if(alive > 0)
    {
        startProfile("Serve");

        count++;
        QString buffer;
        QTextStream stream(&buffer);
        // The following operation is threadsafe.
        startProfile("Fetch");
        subjectList->read(stream, true);
        stopProfile("Fetch");

        startProfile("Wait");
        listMutex.lock();
        stopProfile("Wait");

        // for each connection
        for(QList<ServerConnection *>::iterator i =  connections.begin(); i != connections.end(); i++)
        {
            QTcpSocket *s = (*i)->socket;
            if(s->state() != QAbstractSocket::ConnectedState) continue;

            QString d = QString("%1\nEND\r\n").arg(buffer);

            startProfile("Write");
            int written = s->write(d.toUtf8());
            stopProfile("Write");

            if(written == -1)
            {
                emit outMessage(QString(" Error writing to %1").arg(s->peerAddress().toString()));
            }
            else
            {
                s->flush();
            }
        }

        listMutex.unlock();

        stopProfile("Serve");
    }

    working = false;


    startProfile("Other");


}
void ProtoConnect::connectToMaster(QString ipAddress, int serverPort, ProtocolHandler * protocolHandler){

    QTcpSocket *socket = new QTcpSocket(this);

    //making sure it is disconnectedclose();

    socket->connectToHost(ipAddress, serverPort);

    //wait for one second for connection
    if(!socket->waitForConnected(1000)){
        //error
        qDebug()<<"Error when connecting";
        return;
    }

    SocketClient *socketClient = new SocketClient(protocolHandler, socket);

    //connect(socket, SIGNAL(connected()), socketClient, SLOT(connected()));
    connect(socket, SIGNAL(readyRead()), socketClient, SLOT(readyRead()));
    connect(socket, SIGNAL(disconnected()), socketClient, SLOT(disconnected()));

    //write to the server to connect
    socket->write("||Hello AppMan||");
    socket->flush();

    //finally set the socket so that the network can use it
    protocolHandler->setSocket(socket);
}
Example #6
0
/**
 * @details
 * Send dataSupport Information to connected clients
 */
void TCPConnectionManager::_sendNewDataTypes()
{
    DataSupportResponse res( types() );

    clients_t clientListCopy;
    {
        // control access to the _clients
        QMutexLocker locker(&_mutex);
        clientListCopy = _clients[_dataSupportStream];
    }

    // iterate over all clients subscribed to the data support channel
    for(int i = 0; i < clientListCopy.size(); ++i ) {

        QTcpSocket* client =  clientListCopy[i];

        // Send data to client
        try {
            //std::cout << "Sending to:" << client->peerName().toStdString() << std::endl;
            Q_ASSERT( client->state() == QAbstractSocket::ConnectedState );
            _protocol->send(*client, res);
            client->flush();
            //std::cerr <<  "TCPConnectionManager: sending newdata types to client" << std::endl;
        }
        catch ( ... )
        {
            // kill the client if anything goes wrong
            std::cerr <<  "TCPConnectionManager: failed to send data to client" << std::endl;
            _killClient(client);
        }
    }
}
Example #7
0
void streamLoop(qintptr socketDesc, QQueue<QByteArray> &queue, bool& streaming) {

    QTcpSocket* socket = new QTcpSocket();
    // TCP_NODELAY + disable Nagle's algorithm
    socket->setSocketOption(QAbstractSocket::LowDelayOption, QVariant::fromValue(1));
    // Internetwork control
    socket->setSocketOption(QAbstractSocket::TypeOfServiceOption, QVariant::fromValue(192));
    socket->setSocketDescriptor(socketDesc);
    socket->readAll();

    QByteArray ContentType = ("HTTP/1.1 200 OK\r\n" \
                              "Server: test\r\n" \
                              "Cache-Control: no-cache\r\n" \
                              "Cache-Control: private\r\n" \
                              "Connection: close\r\n"\
                              "Pragma: no-cache\r\n"\
                              "Content-Type: multipart/x-mixed-replace; boundary=--boundary\r\n\r\n");

    socket->write(ContentType);

    while((socket->state() != QAbstractSocket::ClosingState ||
           socket->state() != QAbstractSocket::UnconnectedState) &&
           socket->state() == QAbstractSocket::ConnectedState &&
           streaming) {

        if(queue.empty()) { // no new frame available
            continue;
        }

        // make sure that the queue doesn't grow too big or
        // the OOM killer will kick in
        if(queue.length() > 20) {
            queue.clear();
            continue;
        }

        QByteArray boundary = ("--boundary\r\n" \
                               "Content-Type: image/jpeg\r\n" \
                               "Content-Length: ");

        QByteArray img  = queue.dequeue();
        boundary.append(QString::number(img.length()));
        boundary.append("\r\n\r\n");

        socket->write(boundary);
        socket->waitForBytesWritten();
        boundary.clear();
        socket->write(img);
        socket->waitForBytesWritten();
        img.clear();
    }

    socket->flush();
    socket->abort();
    socket->deleteLater();
    streaming = false;
    queue.clear();
    return;
}
Example #8
0
void MyServer::newConnection()
{
    QTcpSocket *socket = server->nextPendingConnection();

    socket->write("Bonjour est bienvenue!\r\n");
    socket->flush();
    socket->waitForBytesWritten(3000);
    socket->close();
}
Example #9
0
void ConnectionListener::incomingConnection(qintptr socketDescriptor)
{
    if (m_accept) {
        emit log("Listener", "New connection: accepted.");
        m_accept = false;
        emit clientSuccessfullyConnected();

        m_proxy.reset(new Proxy(m_mapData,
                                m_pathMachine,
                                m_prespammedPath,
                                m_groupManager,
                                m_mumeClock,
                                m_mapCanvas,
                                socketDescriptor,
                                this));

        if (getConfig().connection.proxyThreaded) {
            m_thread.reset(new QThread);
            m_proxy->moveToThread(m_thread.get());

            // Proxy destruction stops the thread which then destroys itself on completion
            connect(m_proxy.get(), &QObject::destroyed, m_thread.get(), &QThread::quit);
            connect(m_thread.get(), &QThread::finished, m_thread.get(), &QObject::deleteLater);
            connect(m_thread.get(), &QObject::destroyed, this, [this]() {
                m_accept = true;
                m_proxy.release();
                m_thread.release();
            });

            // Make sure if the thread is interrupted that we kill the proxy
            connect(m_thread.get(), &QThread::finished, m_proxy.get(), &QObject::deleteLater);

            // Start the proxy when the thread starts
            connect(m_thread.get(), &QThread::started, m_proxy.get(), &Proxy::start);
            m_thread->start();

        } else {
            connect(m_proxy.get(), &QObject::destroyed, this, [this]() {
                m_accept = true;
                m_proxy.release();
            });
            m_proxy->start();
        }

    } else {
        emit log("Listener", "New connection: rejected.");
        QTcpSocket tcpSocket;
        if (tcpSocket.setSocketDescriptor(socketDescriptor)) {
            QByteArray ba("\033[1;37;41mYou can't connect to MMapper more than once!\r\n"
                          "Please close the existing connection.\033[0m\r\n");
            tcpSocket.write(ba);
            tcpSocket.flush();
            tcpSocket.disconnectFromHost();
            tcpSocket.waitForDisconnected();
        }
    }
}
Example #10
0
void ServerCore::processNewDevice(QVariantMap& dataMap)
{
	bool isSelfBroadcast = dataMap.contains(JSON_KEY_COMMAND) && dataMap[JSON_KEY_COMMAND] == CMD_QUERY
		&& (!dataMap.contains(JSON_KEY_UID) || !dataMap.contains(JSON_KEY_DISPLAYNAME)
			|| !dataMap.contains(JSON_KEY_IP));

	if (isSelfBroadcast)
	{
		return;
	}

	QString deviceUID = dataMap[JSON_KEY_UID].toString();
	QString deviceName = dataMap[JSON_KEY_DISPLAYNAME].toString();
	QString deviceIP = dataMap[JSON_KEY_IP].toString();
	QString deviceType = dataMap[JSON_KEY_TYPE].toString();

	DeviceInfo devInfo(deviceUID, deviceName, deviceIP, deviceType);
	DeviceManagerModule()->AddDevice(deviceUID, devInfo);

	QVariantMap paramMap;
	paramMap.insert(JSON_KEY_SEQ, 1234);

	QTcpSocket *socket = new QTcpSocket(this);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		parseSupportCmds(deviceUID, byteArray);
		Q_EMIT deviceAdded(deviceUID);
		socket->disconnectFromHost();
	});

	QObject::connect(socket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
		[=](QAbstractSocket::SocketError socketError)
	{
		qDebug() << "Socket Error" << socketError;
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	socket->connectToHost(deviceIP, PORT_SERVER_BROADCAST, QIODevice::ReadWrite);

	socket->waitForConnected();

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::QUERY_DEVICE_SUPPORT_CMDS, paramMap);

	socket->write(jsonCmd.toLatin1());
	socket->flush();

	socket->waitForBytesWritten();
	socket->waitForReadyRead();

	
}
Example #11
0
void TcpServer::readData()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());

    qDebug() << socket->readAll();

    QByteArray b(10,'a');
    socket->write(b);
    socket->flush();
}
bool NetworkManager::sendData(int connectionID, const unsigned char* data, int size)
{
    if(connectionID < 0)
        return false;

    QTcpSocket* socket = mConnections[connectionID];
    socket->write((const char*)data, size);

    return socket->flush();
}
Example #13
0
//----------------------------------------------------------------------------------
void tst_QTcpServer::clientServerLoop()
{
    QTcpServer server;

    QSignalSpy spy(&server, SIGNAL(newConnection()));

    QVERIFY(!server.isListening());
    QVERIFY(!server.hasPendingConnections());
    QVERIFY(server.listen(QHostAddress::Any, 11423));
    QVERIFY(server.isListening());

    QTcpSocket client;

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.serverAddress() == QHostAddress::Any))
        serverAddress = server.serverAddress();

    client.connectToHost(serverAddress, server.serverPort());
    QVERIFY(client.waitForConnected(5000));

    QVERIFY(server.waitForNewConnection(5000));
    QVERIFY(server.hasPendingConnections());

    QCOMPARE(spy.count(), 1);

    QTcpSocket *serverSocket = server.nextPendingConnection();
    QVERIFY(serverSocket != 0);

    QVERIFY(serverSocket->write("Greetings, client!\n", 19) == 19);
    serverSocket->flush();

    QVERIFY(client.waitForReadyRead(5000));
    QByteArray arr = client.readAll();
    QCOMPARE(arr.constData(), "Greetings, client!\n");

    QVERIFY(client.write("Well, hello to you!\n", 20) == 20);
    client.flush();

    QVERIFY(serverSocket->waitForReadyRead(5000));
    arr = serverSocket->readAll();
    QCOMPARE(arr.constData(), "Well, hello to you!\n");
}
void MyServer::newConnection()
{
    QTcpSocket *socket = server->nextPendingConnection();

    socket->write("<h1>Hello Client</h1>\r\n");
    socket->flush();

    socket->waitForBytesWritten(3000);

    socket->close();
}
Example #15
0
void ConnectServer::newConnection(){


    QTcpSocket * socket = server->nextPendingConnection();
    socket->write("Connected to Mp3 App\r\n");
    socket->flush();

    socket->waitForBytesWritten(3000);
    socket->close();

}
Example #16
0
void TCPServer::nConnection()
{
    QTcpSocket *socket = server->nextPendingConnection();

    socket->write("hello client\r\n");
    socket->flush();

    socket->waitForBytesWritten(3000);

    socket->close();
}
Example #17
0
GameWindowServeur::recupConnection()
{
    QTcpSocket *socket = m_server->nextPendingConnection();

    socket->write("Hello client");
    socket->flush();

    m_clients[m_numNextClient++] = socket;

    //socket->close();
}
Example #18
0
void QtNetworkPeerPrivate::sendMessage(const QByteArray &message)
{
    qDebug() << "sendMessage" << message;

    foreach (const QHostAddress &address, m_acceptedOutboundConnections.keys()) {
        qDebug() << "sendMessage" << address;
        QTcpSocket *socket = m_acceptedOutboundConnections.value(address);
        qDebug() << "socket" << socket->isValid() << socket->isOpen();
        socket->write(message);
        socket->flush();
    }
}
Example #19
0
void TaskForTcpServer::run()
{
    if(!socketDescriptor) return;

        QTcpSocket socket;
        socket.setSocketDescriptor(socketDescriptor);
        //to do

        socket.write("From server: hello world");
        socket.flush();
        socket.waitForBytesWritten();
        socket.close();
}
Example #20
0
void QTServer::SlotStopScript(const int &nRow) {
    QTableWidgetItem* pItemAcc = ui.tableWidget->item(nRow, 0);
    QTcpSocket* pTcpSocket = (QTcpSocket*)(pItemAcc->data(Qt::UserRole + 0x200)).toInt();
    if (pTcpSocket) {
        SOCKET_INFO socket_info;
        RtlZeroMemory(&socket_info, sizeof(SOCKET_INFO));
        socket_info.message = SOCKET_MESSAGE::StopScript;
        QByteArray datasend;
        datasend.append((const char*)&socket_info);
        pTcpSocket->write((const char*)&socket_info, sizeof(SOCKET_INFO));
        pTcpSocket->flush();
        QTableWidgetItem* pItemStatus = ui.tableWidget->item(nRow, 7);
        pItemStatus->setData(Qt::DisplayRole, QStringLiteral("成功登陆"));
    }
}
void PanoServerTCP::Write(const QByteArray& msg, QTcpSocket* receiver, QTcpSocket* exclusion) {
  if (receiver) {
    receiver->write(msg);
    receiver->flush();
  } else {
    for (vector<TcpConnection>::iterator i = connections_.begin();
         i != connections_.end();
         ++i) {
      QTcpSocket* socket = i->socket;
      if (socket != exclusion) {
        socket->write(msg);
        socket->flush();
      }
    }
  }
}
Example #22
0
bool Server::SendData(QString message)
{
    bool result = false;
    QTcpSocket* tcpSocket = getRemoteSocket();
    if (tcpSocket && tcpSocket->state()==QAbstractSocket::ConnectedState && tcpSocket->isWritable()) {
        emit write_message(tr("Sending data (size=%1) to server. Content: \"%2\"").arg(message.length()).arg(message));
        tcpSocket->write(message.toLocal8Bit());
        result = tcpSocket->waitForBytesWritten();
        if (!result) {
            emit error(tr("Sending error: %1").arg(tcpSocket->errorString()));
        } else {
            tcpSocket->flush();
        }
    }
    return result;
}
Example #23
0
/**
 * @details
 * Send data to connected clients
 */
void TCPConnectionManager::send(const QString& streamName, const DataBlob* blob)
{

    QMutexLocker sendlocker(&_sendMutex);

    // Check if there are any client reading streamName type data
    if (_clients.contains(streamName) ) {
        clients_t clientListCopy;
        {
            // control access to the _clients
            QMutexLocker locker(&_mutex);
            clientListCopy = _clients[streamName];
        }

        for(int i = 0; i < clientListCopy.size(); ++i ) {

            QTcpSocket* client =  clientListCopy[i];

            // Send data to client
            try {
                //std::cout << "Sending blob of type " << blob->type().toStdString()
                //          << " on stream " << streamName.toStdString() << " to:"
                //          << client->peerName().toStdString() << std::endl;
                Q_ASSERT( client->state() == QAbstractSocket::ConnectedState );
                _protocol->send(*client, streamName, *blob);
                client->flush();
            }
            catch ( ... )
            {
                // kill the client if anything goes wrong
                std::cerr <<  "TCPConnectionManager: failed to send data to client" << std::endl;
                _killClient(client);
            }
        }
    }
    emit sent(blob); // let any blocked sends continue
                     // now the blob is sent.

    // Ensure we track the data streams and inform any interested
    // clients of updates.
    if( !_seenTypes.contains(streamName) )
    {
        _seenTypes.insert(streamName);
        _sendNewDataTypes();
    }
}
Example #24
0
void Graph::onConnected()
{
	QTcpSocket *socket = (QTcpSocket *)sender();
	QVector<ident_t> ids;
	for(Stats::iterator s = stats.begin(); s != stats.end(); ++s)
		if(socket->peerAddress() == QHostAddress(vtl::app->sourcersContainer()->server(s.key()->getIp()).host()))
	{
		ident_t id = s.key()->ident();
		if(id != -1) ids << id;
	}
	int n = ids.size();
	if(!n) return;
	qDebug() << " pribor request: " << n << ids;
	socket->write((const char *)&n, sizeof(n));
	socket->write((const char *)ids.data(), n*sizeof(ident_t));
	socket->flush();
}
Example #25
0
bool sendAgentMessage(int port, const QString& message) {
  bool result = true;

  QTcpSocket sck;
  sck.connectToHost(QHostAddress::LocalHost,port);
  sck.waitForConnected(1000);

  if (sck.state() == QAbstractSocket::ConnectedState) {
    sck.write(message.toUtf8());
    sck.flush();
  }
  else {
    result = false;
  }

  sck.close();
  return result;
}
Example #26
0
void QTServer::SlotStartScript(const int &nRow) {
    QTableWidgetItem* pItemAcc = ui.tableWidget->item(nRow, 0);
    QTcpSocket* pTcpSocket = (QTcpSocket*)(pItemAcc->data(Qt::UserRole + 0x200)).toInt();
    if (pTcpSocket) {
        SOCKET_INFO socket_info;
        RtlZeroMemory(&socket_info, sizeof(SOCKET_INFO));
        socket_info.message = SOCKET_MESSAGE::StartScript;
        QTableWidgetItem* pItemScript = ui.tableWidget->item(nRow, 3);
        QString qstrScript = pItemScript->data(Qt::DisplayRole).toString(); // 脚本
        std::string strScript = std::string((const char*)qstrScript.toLocal8Bit());
        strcpy_s(socket_info.szAccOrScript, strScript.c_str());
        QByteArray datasend;
        datasend.append((const char*)&socket_info);
        pTcpSocket->write((const char*)&socket_info, sizeof(SOCKET_INFO));
        pTcpSocket->flush();
        QTableWidgetItem* pItemStatus = ui.tableWidget->item(nRow, 7);
        pItemStatus->setData(Qt::DisplayRole, QStringLiteral("挂机中"));
    }
}
Example #27
0
void OAuthenticator::NewConnection() {
  QTcpSocket* socket = server_.nextPendingConnection();
  server_.close();

  QByteArray buffer;

  NewClosure(socket, SIGNAL(readyRead()),
             this, SLOT(RedirectArrived(QTcpSocket*, QByteArray)), socket, buffer);

  // Everything is bon.  Prepare and display the success page.
  QFile page_file(":oauthsuccess.html");
  page_file.open(QIODevice::ReadOnly);
  QString page_data = QString::fromLatin1(page_file.readAll());

  // Translate the strings inside
  QRegExp tr_regexp("tr\\(\"([^\"]+)\"\\)");
  int offset = 0;
  forever {
    offset = tr_regexp.indexIn(page_data, offset);
    if (offset == -1) {
      break;
    }

    page_data.replace(offset, tr_regexp.matchedLength(),
                      tr(tr_regexp.cap(1).toAscii()));
    offset += tr_regexp.matchedLength();
  }

  // Add the tick image.
  QBuffer image_buffer;
  image_buffer.open(QIODevice::ReadWrite);
  QApplication::style()->standardIcon(QStyle::SP_DialogOkButton)
      .pixmap(16).toImage().save(&image_buffer, "PNG");

  page_data.replace("@IMAGE_DATA@", image_buffer.data().toBase64());

  socket->write("HTTP/1.0 200 OK\r\n");
  socket->write("Content-type: text/html;charset=UTF-8\r\n");
  socket->write("\r\n\r\n");
  socket->write(page_data.toUtf8());
  socket->flush();
}
Example #28
0
void
ITunesScript::transmit( const QString& data )
{
    // thread-safe, basically
    int const port = m_listener->GetPort();

    LOGL( 3, "ITunesScript data being sent " << data << " to port " << port );

    QTcpSocket socket;
    socket.connectToHost( QHostAddress::LocalHost, port );
    if ( socket.waitForConnected( 1000 ) ) //FIXME hangs GUI thread?
    {
        int bytesWritten = socket.write( data.toUtf8() );
        socket.flush();
        socket.waitForDisconnected( 1000 ); //FIXME hangs?

        if ( bytesWritten == -1 )
        {
            LOGL( 1, "Sending submission through socket failed." )
        }
    }
Example #29
0
void QtServiceSysPrivate::slotReady()
{
    QTcpSocket *s = (QTcpSocket *)sender();
    cache[s] += QString(s->readAll());
    QString cmd = getCommand(s);
    while (!cmd.isEmpty()) {
        bool retValue = false;
        if (cmd == QLatin1String("terminate")) {
            if (!(serviceFlags & QtServiceBase::CannotBeStopped)) {
                QtServiceBase::instance()->stop();
                QCoreApplication::instance()->quit();
                retValue = true;
            }
        } else if (cmd == QLatin1String("pause")) {
            if (serviceFlags & QtServiceBase::CanBeSuspended) {
                QtServiceBase::instance()->pause();
                retValue = true;
            }
        } else if (cmd == QLatin1String("resume")) {
            if (serviceFlags & QtServiceBase::CanBeSuspended) {
                QtServiceBase::instance()->resume();
                retValue = true;
            }
        } else if (cmd == QLatin1String("alive")) {
            retValue = true;
        } else if (cmd.length() > 4 && cmd.left(4) == QLatin1String("num:")) {
            cmd = cmd.mid(4);
            QtServiceBase::instance()->processCommand(cmd.toInt());
            retValue = true;
        }
        QString retString;
        if (retValue)
            retString = QLatin1String("true");
        else
            retString = QLatin1String("false");
        s->write(retString.toLatin1().constData());
        s->flush();
        cmd = getCommand(s);
    }
}
// Test buffered socket being properly closed on remote disconnect
void tst_QAbstractSocket::serverDisconnectWithBuffered()
{
    QTcpServer tcpServer;
#ifndef QT_NO_SSL
    QSslSocket testSocket;
#else
    QTcpSocket testSocket;
#endif

    QVERIFY(tcpServer.listen(QHostAddress::LocalHost));
    testSocket.connectToHost(tcpServer.serverAddress(), tcpServer.serverPort());
    // Accept connection on server side
    QVERIFY(tcpServer.waitForNewConnection(5000));
    QTcpSocket *newConnection = tcpServer.nextPendingConnection();
    // Send one char and drop link
    QVERIFY(newConnection != NULL);
    QVERIFY(newConnection->putChar(0));
    QVERIFY(newConnection->flush());
    delete newConnection;

    QVERIFY(testSocket.waitForConnected(5000)); // ready for write
    QVERIFY(testSocket.state() == QAbstractSocket::ConnectedState);

    QSignalSpy spyStateChanged(&testSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
    QSignalSpy spyDisconnected(&testSocket, SIGNAL(disconnected()));

    QVERIFY(testSocket.waitForReadyRead(5000)); // have one char already in internal buffer
    char buf[128];
    QCOMPARE(testSocket.read(buf, sizeof(buf)), Q_INT64_C(1));
    if (testSocket.state() != QAbstractSocket::UnconnectedState) {
        QVERIFY(testSocket.waitForDisconnected(5000));
        QVERIFY(testSocket.state() == QAbstractSocket::UnconnectedState);
    }
    // Test signal emitting
    QVERIFY(spyDisconnected.count() == 1);
    QVERIFY(spyStateChanged.count() > 0);
    QVERIFY(qvariant_cast<QAbstractSocket::SocketState>(spyStateChanged.last().first())
            == QAbstractSocket::UnconnectedState);
}