Esempio n. 1
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");
}
Esempio n. 2
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;
}
Esempio n. 3
0
bool CHttpServer::Listen(int Port)
{
	QTcpServer* pListener = new QTcpServer(this);
	pListener->listen(QHostAddress::Any, Port);
    if (!pListener->isListening()) 
	{
		delete pListener;
		return false;
	}
	connect(pListener, SIGNAL(newConnection()), this, SLOT(OnConnection()));

	m_Listners.insert(Port, pListener);
	return true;
}
Esempio n. 4
0
void tst_QTcpServer::constructing()
{
    QTcpServer socket;

    // Check the initial state of the QTcpSocket.
    QCOMPARE(socket.isListening(), false);
    QCOMPARE((int)socket.serverPort(), 0);
    QCOMPARE(socket.serverAddress(), QHostAddress());
    QCOMPARE(socket.maxPendingConnections(), 30);
    QCOMPARE(socket.hasPendingConnections(), false);
    QCOMPARE(socket.socketDescriptor(), -1);
    QCOMPARE(socket.serverError(), QAbstractSocket::UnknownSocketError);

    // Check the state of the socket layer?
}
Esempio n. 5
0
        QTcpServer* DccCommon::createServerSocketAndListen( QObject* parent, QString* failedReason, int minPort, int maxPort )
        {
            QTcpServer* socket = new QTcpServer( parent );

            if ( minPort > 0 && maxPort >= minPort )  // ports are configured manually
            {
                // set port
                bool found = false;                       // whether succeeded to set port
                for ( int port = minPort; port <= maxPort ; ++port )
                {
                    bool success = socket->listen( QHostAddress::Any, port );
                    if ( ( found = ( success && socket->isListening() ) ) )
                        break;
                    socket->close();
                }
                if ( !found )
                {
                    if ( failedReason )
                        *failedReason = i18n( "No vacant port" );
                    delete socket;
                    return 0;
                }
            }
            else
            {
                // Let the operating system choose a port
                if ( !socket->listen() )
                {
                    if ( failedReason )
                        *failedReason = i18n( "Could not open a socket" );
                    delete socket;
                    return 0;
                }
            }

            return socket;
        }
//Thread run
void ViewerHandler::run() {
    WDEF;
    pSocket = 0;
	int i;

    //Request and voiceClient creation and initialization (using ViewerHandler::requestQueue)

    //TalkingThread tt(this->request);
    this->tt = new TalkingThread(*this);
	this->connection = new Connection(*this, *(this->tt));
    this->request = new Request(*this, requestQueue, *connection);

    //VoiceClient deals with messages originated in the client
    VoiceClient voiceClient(requestQueue);
    voiceClient.start();

    WDEBUG1("ViewerHandler: whisper started");

    //Server listening to localhost:44125
    QTcpServer server;
    server.listen(QHostAddress::LocalHost, (quint16)44125);

    WDEBUG3("ViewerHandler: waiting for connection to %s:%d", "127.0.0.1", 44125);

    //Timeout
    if(!server.waitForNewConnection(10000))
        WTHROW1("no connection found");

    // Getting ViewerHandler::pSocket
    pSocket = server.nextPendingConnection();

    if (!pSocket)
        WTHROW1("ViewerHandler: invalid socket - terminating");

    WDEBUG1("ViewerHandler: entering main loop");
	initialized();
    // Main request processing loop
    for(;;) {

        if (pSocket->bytesAvailable() > 0 || pSocket->waitForReadyRead(10000)) {

            WDEBUG1("ViewerHandler: reading data from buffer");

            //Reads the whole buffer
            QString qsData = pSocket->readAll();

			// TODO: it might be that this is not the only request in the string
			//       -> the request should be handled properly
			if(qsData.contains("Connector.InitiateShutdown.1")) {
				WDEBUG1("ViewerHandler: Connector.InitiateShutdown.1 received - doing nothing");
                //break;
			}

            //Splits the buffer in several requests
            QStringList& rlRequests = qsData.split("\n\n\n", QString::SkipEmptyParts);

            //Counts number of requests
            int count = rlRequests.size();

			WDEBUG2("ViewerHandler: %d request(s) received", count);

            //For each request
            for (i=0; i<count; i++) {
				WDEBUG3("ViewerHandler: Sending request %d to be handled: \n%s\n", i, rlRequests[i].toAscii().data());

                //handles it
                if(this->request->handle(rlRequests[i])) {
					WDEBUG1("ViewerHandler: error while handling request - next request");
                    continue;
                }
            }
        //If there're no requests received
        } else {
            //Checks if socket is still valid and disconnect if not
            WDEBUG2("Socket state: %d", (int) pSocket->state());
            if(pSocket->state() != QAbstractSocket::ConnectedState) {
                WDEBUG1("Socket is no more connected - closing program");
				WWRITE1 ("Socket no more connected - shutting down");

                break;
            }
        }
    }

    WEND:
				
	WDEBUG1("ViewerHandler: sending quit to the main application");
	qApp->quit();

	while (!is_shutdown()) {
		//wait to receive shutdown from main thread
		WDEBUG1("ViewerHandler: waiting to receive shutdown");
		QThread::msleep(1000);
		//vhSleep(1000);
	}
	WDEBUG1("ViewerHandler: shutdown received");

    WDEBUG1("ViewerHandler: stopping VoiceClient...");
    voiceClient.end();

    voiceClient.wait();
	WDEBUG1("Viewer Handler: VoiceClient has terminated");

    //WDEBUG1("Stopping talkingThread...");
    //if(this->tt->isRunning())this->tt->quit();
    WDEBUG1("ViewerHandler: stopping TalkingThread...");
    //voiceClient.end();

	if(tt != 0) {
		tt->end();
		tt->wait();
		delete tt;
		tt=0;
		WDEBUG1("Viewer Handler: TalkingThread has terminated");
	}

    WDEBUG1("ViewerHandler: finishing...");

	if (pSocket){
		pSocket->close();

		WDEBUG2("ViewerHandler: pSocket status: %s", pSocket->state() == QAbstractSocket::UnconnectedState ? "Unconnected" : "Still Up");
		pSocket = 0;
	}
	server.close();

	WDEBUG2("ViewerHandler: server status: %s", server.isListening() ? "Listening" : "Shutdown");

    return;
}