MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // get ipv4 address list
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    for(int i = 0; i < ipAddressesList.size(); ++i)
    {
        QTcpServer testServer;
        if( ipAddressesList[i].toIPv4Address() && testServer.listen(ipAddressesList[i], 9876) ) {
            testServer.close();
            ui->comboBox->addItem(ipAddressesList[i].toString());
        }
    }

    ui->lineEditHostname->setText(QHostInfo::localHostName());

    IPv4 = ui->comboBox->currentText();
    serverPort = ui->spinBoxPort->value();
    serverState = ServerStop;

    runningDay = runningSec = runningMin = runningHour = 0;
    timer = new QTimer(this);
    timer->start(1000); // msec

    db = NULL;
    server = NULL;

    connect(timer, SIGNAL(timeout()),
            this, SLOT(runningTimeChange()));
}
int ServerManager::createListeningSocket(const QHostAddress &address, quint16 port)
{
    int sd = 0;
    QTcpServer server;

    if (!server.listen(address, port)) {
        qCritical("listen failed");
        return sd;
    }

    sd = ::fcntl(server.socketDescriptor(), F_DUPFD, 0);
#if defined(FD_CLOEXEC)
    ::fcntl(sd, F_SETFD, 0);
#endif
    server.close();
    return sd;
}
Exemple #3
0
void ServerPool::close(void)
{
    QTcpServer *server;
    while (!m_tcpServers.isEmpty())
    {
        server = m_tcpServers.takeLast();
        server->disconnect();
        server->close();
        delete server;
    }

    QUdpSocket *socket;
    while (!m_udpSockets.isEmpty())
    {
        socket = m_udpSockets.takeLast();
        socket->disconnect();
        socket->close();
        delete socket;
    }
}
/*!
  Listen a port for connections on a socket.
  This function must be called in a tfmanager process.
 */
int TApplicationServerBase::nativeListen(const QHostAddress &address, quint16 port, OpenFlag flag)
{
    int sd = 0;
    QTcpServer server;

    if (!server.listen(address, port)) {
        tSystemError("Listen failed  port:%d", port);
        return sd;
    }

    sd = duplicateSocket(server.socketDescriptor()); // duplicate

    if (flag == CloseOnExec) {
        ::fcntl(sd, F_SETFD, ::fcntl(sd, F_GETFD) | FD_CLOEXEC);
    } else {
        ::fcntl(sd, F_SETFD, 0);  // clear
    }
    ::fcntl(sd, F_SETFL, ::fcntl(sd, F_GETFL) | O_NONBLOCK);  // non-block

    server.close();
    return sd;
}
Exemple #5
0
void ServerPool::close(void)
{
    QTcpServer *server;
    while (!m_tcpServers.isEmpty())
    {
        server = m_tcpServers.takeLast();
        server->disconnect();
        server->close();
        server->deleteLater();
    }

    QUdpSocket *socket;
    while (!m_udpSockets.isEmpty())
    {
        socket = m_udpSockets.takeLast();
        socket->disconnect();
        socket->close();
        socket->deleteLater();
    }

    m_listening = false;
}
static PyObject *meth_QTcpServer_close(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        QTcpServer *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QTcpServer, &sipCpp))
        {
            Py_BEGIN_ALLOW_THREADS
            sipCpp->close();
            Py_END_ALLOW_THREADS

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QTcpServer, sipName_close, doc_QTcpServer_close);

    return NULL;
}
Exemple #7
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;
        }
void tst_QSocketNotifier::unexpectedDisconnection()
{
    /*
      Given two sockets and two QSocketNotifiers registered on each
      their socket. If both sockets receive data, and the first slot
      invoked by one of the socket notifiers empties both sockets, the
      other notifier will also emit activated(). This results in
      unexpected disconnection in QAbstractSocket.

      The use case is that somebody calls one of the
      waitFor... functions in a QSocketNotifier activated slot, and
      the waitFor... functions do local selects that can empty both
      stdin and stderr while waiting for fex bytes to be written.
    */

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

    NATIVESOCKETENGINE readEnd1;
    readEnd1.initialize(QAbstractSocket::TcpSocket);
    readEnd1.connectToHost(server.serverAddress(), server.serverPort());
    QVERIFY(readEnd1.waitForWrite());
    QVERIFY(readEnd1.state() == QAbstractSocket::ConnectedState);
    QVERIFY(server.waitForNewConnection());
    QTcpSocket *writeEnd1 = server.nextPendingConnection();
    QVERIFY(writeEnd1 != 0);

    NATIVESOCKETENGINE readEnd2;
    readEnd2.initialize(QAbstractSocket::TcpSocket);
    readEnd2.connectToHost(server.serverAddress(), server.serverPort());
    QVERIFY(readEnd2.waitForWrite());
    QVERIFY(readEnd2.state() == QAbstractSocket::ConnectedState);
    QVERIFY(server.waitForNewConnection());
    QTcpSocket *writeEnd2 = server.nextPendingConnection();
    QVERIFY(writeEnd2 != 0);

    writeEnd1->write("1", 1);
    writeEnd2->write("2", 1);

    writeEnd1->waitForBytesWritten();
    writeEnd2->waitForBytesWritten();

    writeEnd1->flush();
    writeEnd2->flush();

    UnexpectedDisconnectTester tester(&readEnd1, &readEnd2);

    QTimer timer;
    timer.setSingleShot(true);
    timer.start(30000);
    do {
        // we have to wait until sequence value changes
        // as any event can make us jump out processing
        QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents);
        QVERIFY(timer.isActive()); //escape if test would hang
    }  while(tester.sequence <= 0);

    QVERIFY(readEnd1.state() == QAbstractSocket::ConnectedState);
    QVERIFY(readEnd2.state() == QAbstractSocket::ConnectedState);

    QCOMPARE(tester.sequence, 2);

    readEnd1.close();
    readEnd2.close();
    writeEnd1->close();
    writeEnd2->close();
    server.close();
}
//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;
}
Exemple #10
0
//----------------------------------------------------------------------------------
void tst_QTcpServer::crashTests()
{
    QTcpServer server;
    server.close();
    QVERIFY(server.listen());
}
Exemple #11
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    for(int i = 0 ; i < argc; i++){
        qDebug() << argv[i] << endl;
    }

    if(argc >= 4)
    {
        //Getting first argument for application
        QString arg = argv[1];
        //Sending mode
        if(arg == "send")
        {
            QTcpSocket *tcpSocket = new QTcpSocket(&a);
            QString port = argv[3];
            tcpSocket->connectToHost(QHostAddress(argv[2]), port.toInt());
            if(!tcpSocket->waitForConnected(10*1000)){
                qDebug() << "Connection cant be established to host: " << argv[2] << ", at port: " << port << endl;
            }else{
                //Sending mode = file
                QString type(argv[4]);
                if(type == "file")
                {
                    QFile file(argv[5]);
                    if(!file.open(QFile::ReadOnly))
                    {
                        qDebug() << "Cannot open file" << endl;
                    }else
                    {
                        qDebug() << "File size in bytes: " << file.size() << endl;
                        int counter = 0;
                        //Divide file into chunks of 300KB
                        int chunkSize = 3 * 100000;
                        while(counter < file.size()){
                                if(!file.seek(counter)){
                                    qDebug() << "Cant seek the file to : " << counter << endl;
                                }else{
                                    QByteArray buffer = file.read(chunkSize);
                                    if(!buffer.isEmpty()){
                                        int bytesWritten = tcpSocket->write(buffer);
                                        counter += bytesWritten;
                                        if(!tcpSocket->waitForBytesWritten(10*1000))
                                        {
                                            qDebug() << "Error no bytes written" << tcpSocket->errorString() << endl;
                                        }else
                                        {
                                            qDebug() << "Bytes for writting: " << buffer.size() << ", " << bytesWritten << " bytes written. " << endl;
                                        }
                                    }else{
                                      qDebug() << "0 bytes read from file, error: " << file.errorString() << endl;
                                      break;
                                    }
                                }
                        }

                    }
                //Sending mode = string
                }else if(type == "string")
                {
                    QByteArray data = argv[5];
                    int bytesWritten = tcpSocket->write(data);
                    if(!tcpSocket->waitForBytesWritten(10000))
                    {
                        qDebug() << "Error no bytes written" << tcpSocket->errorString() << endl;
                    }else
                    {
                        qDebug() << bytesWritten << " bytes written. " << endl;
                    }
                }else{
                    qDebug() << "Unknown sending format " << endl;
                }
            }
            tcpSocket->close();
            delete tcpSocket;
        //Receiving mode
        }else if(arg == "receive")
        {
            QTcpServer *tcpServer = new QTcpServer(&a);
            QString port = argv[3];
            if(!tcpServer->listen(QHostAddress(QString(argv[2])),port.toInt())){
                qDebug() << "Error, could not start listening, " << tcpServer->serverError() << endl;
            }else{

                QString fileName;
                QString destinationPath;
                //Getting name and path for the new file from user
                bool tryAgain = true;
                while(tryAgain){
                    qDebug() << "Enter filename for the new file (ex: picture.png) :";
                    QTextStream s(stdin);
                    fileName = s.readLine();
                    qDebug() << "Enter destination path: ";
                    QTextStream d(stdin);
                    destinationPath = d.readLine();
                    if (!fileName.isEmpty() && !destinationPath.isEmpty())
                    {
                        qDebug() << "The destination string: " << destinationPath + fileName;
                        tryAgain = false;
                    }else{
                        qDebug() << "You didnt enter filename, try again" << endl;
                    }
                }

                bool working = true;
                while(working){
                    if(tcpServer->waitForNewConnection(10*1000)){
                        QTcpSocket *sock = tcpServer->nextPendingConnection();
                        sock->waitForReadyRead(10*1000);
                        QByteArray receivedData;
                        QFile file_handle(destinationPath + fileName);
                        //While there is bytes available for receiving, receive them and write chunks of min 300KB to file
                        while(sock->bytesAvailable()){
                            qDebug() << sock->bytesAvailable() << " bytes available for writting" << endl;
                            receivedData.append(sock->readAll());
                            if(receivedData.size() > 3 * 100000){
                                if(!file_handle.isOpen()){
                                    if(!file_handle.open(QFile::WriteOnly | QFile::Append | QFile::Text)){
                                        qDebug() << "Could not open file for writing!" << endl;
                                    }else{
                                        file_handle.write(receivedData);
                                        file_handle.flush();
                                        file_handle.waitForBytesWritten(10*1000);
                                        qDebug() << "Written " << receivedData.size() << " to file. In KB = " << receivedData.size() / 1000 << endl;
                                        receivedData.clear();
                                    }
                                }else{
                                    file_handle.write(receivedData);
                                    file_handle.flush();
                                    file_handle.waitForBytesWritten(10*1000);
                                    qDebug() << "Written " << receivedData.size() << " to file. In KB = " << receivedData.size() / 1000 << endl;
                                    receivedData.clear();
                                }
                            }
                            sock->waitForReadyRead(10*1000);
                        }
                        file_handle.close();
                        //In case there is still data in buffer, but data is smaller than 300KB than append that remaining data to file also
                        if(receivedData.size() != 0){
                            qDebug() << "Preparing to write remaining chunks of data" << endl;
                            if(!file_handle.open(QFile::WriteOnly)){
                                qDebug() << "Could not open file for writing!" << endl;
                            }else{
                                file_handle.write(receivedData);
                                file_handle.flush();
                                file_handle.waitForBytesWritten(10*1000);
                                qDebug() << "Written " << receivedData.size() << " to file. In MB = " << receivedData.size() / 1000000 << endl;
                                receivedData.clear();
                                file_handle.close();
                            }
                        }

                        sock->close();
                        delete sock;
//                        file_thread->deleteLater();

                        qDebug() << "Should i wait for other request? (y/n) default = yes" ;
                        char  answer;
                        cin >> answer;
                        if(answer == 'n'){
                            working = false;
                            tcpServer->close();
                            delete tcpServer;
                        }
                    }else{
                        qDebug() << "No incoming connection" << endl;
                        qDebug() << "Should i check for another request? (Yes / No)" ;
                        char answer;
                        cin >> answer;
                        if(answer == 'n'){
                            working = false;
                            tcpServer->close();
                            delete tcpServer;
                        }
                    }
                }