Ejemplo n.º 1
0
Server::Server(QWidget *parent) : QDialog(parent)
{
    networkSession=0;
    tcpServer=0;
    ui = new Ui::Server;
    ui->setupUi(this);
    val=0;
    ui->quit_button->setAutoDefault(false);

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        networkSession->open();
    } else {
        sessionOpened();
    }
    connect(ui->quit_button, SIGNAL(clicked()), this, SLOT(close()));
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(conn()));
}
Ejemplo n.º 2
0
/**
 * @brief CDiscovery::requestNAMgr provides a shared pointer to the discovery services network
 * access manager. Note that the caller needs to hold his copy of the shared pointer until the
 * network operation has been completed to prevent the manager from being deleted too early.
 * Locking: YES (synchronous)
 * @return
 */
QSharedPointer<QNetworkAccessManager> CDiscovery::requestNAM()
{
	m_pSection.lock();

	QSharedPointer<QNetworkAccessManager> pReturnVal = m_pNetAccessMgr.toStrongRef();
	if ( !pReturnVal )
	{
		// else create a new access manager (will be deleted if nobody is using it anymore)
		pReturnVal = QSharedPointer<QNetworkAccessManager>( new QNetworkAccessManager(),
															&QObject::deleteLater );
		m_pNetAccessMgr = pReturnVal.toWeakRef();

		// Make sure the networkAccessible state is properly initialized.
		QNetworkConfigurationManager manager;
		manager.updateConfigurations();
		pReturnVal->setConfiguration( manager.defaultConfiguration() );
		// QNetworkAccessManager::networkAccessible is not explicitly set when the
		// QNetworkAccessManager is created. It is only set after the network session is
		// initialized. The session is initialized automatically when a network request is made or
		// it can be initialized manually beforehand with QNetworkAccessManager::setConfiguration()
		// or by setting the QNetworkConfigurationManager::NetworkSessionRequired flag.
		// http://www.qtcentre.org/threads/37514-use-of-QNetworkAccessManager-networkAccessible
		// ?s=171a7f69eccb2459cf1cc38507347ead&p=188372#post188372
	}

	m_pSection.unlock();

	return pReturnVal;
}
Ejemplo n.º 3
0
TcpEchoServer::TcpEchoServer(quint16 port, QObject *parent)
:   QObject(parent), tcpServer(0), networkSession(0)
{
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        qDebug() << "Opening network session.";
        networkSession->open();
    } else {
        sessionOpened(port);
    }
}
lc::ClientHelpNotificationServer::ClientHelpNotificationServer( QObject *argParent ) :
    QObject{ argParent },
    hostAddress{ settings->serverIP }
{
    QNetworkConfigurationManager manager;
    if ( manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired ) {
        // Get saved network configuration
        QSettings settings{ QSettings::UserScope, QLatin1String{ "QtProject" } };
        settings.beginGroup( QLatin1String{ "QtNetwork" } );
        const QString id = settings.value( QLatin1String{ "DefaultNetworkConfiguration" } ).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier( id );
        if ( ( config.state() & QNetworkConfiguration::Discovered ) != QNetworkConfiguration::Discovered ) {
            config = manager.defaultConfiguration();
        }
        networkSession = new QNetworkSession{ config, this };
        connect( networkSession, &QNetworkSession::opened,
                 this, &ClientHelpNotificationServer::OpenSession );
        networkSession->open();
    } else {
        OpenSession();
    }

    connect( helpMessageServer, &QTcpServer::newConnection,
             this, &ClientHelpNotificationServer::SendReply );
}
Ejemplo n.º 5
0
//! [0]
AppModel::AppModel(QObject *parent) :
        QObject(parent),
        d(new AppModelPrivate)
{
//! [0]
    d->fcProp = new QQmlListProperty<WeatherData>(this, d,
                                                          forecastAppend,
                                                          forecastCount,
                                                          forecastAt,
                                                          forecastClear);

    d->geoReplyMapper = new QSignalMapper(this);
    d->weatherReplyMapper = new QSignalMapper(this);

    connect(d->geoReplyMapper, SIGNAL(mapped(QObject*)),
            this, SLOT(handleGeoNetworkData(QObject*)));
    connect(d->weatherReplyMapper, SIGNAL(mapped(QObject*)),
            this, SLOT(handleWeatherNetworkData(QObject*)));

//! [1]
    // make sure we have an active network session
    d->nam = new QNetworkAccessManager(this);

    QNetworkConfigurationManager ncm;
    d->ns = new QNetworkSession(ncm.defaultConfiguration(), this);
    connect(d->ns, SIGNAL(opened()), this, SLOT(networkSessionOpened()));
    // the session may be already open. if it is, run the slot directly
    if (d->ns->isOpen())
        this->networkSessionOpened();
    // tell the system we want network
    d->ns->open();
}
Ejemplo n.º 6
0
void
Loco::RunSlippy ()
{
  mainUi.displayMap->SetLocator (locator);
  // Set Internet Access Point
  QNetworkConfigurationManager manager;
  const bool canStartIAP = (manager.capabilities()
                            & QNetworkConfigurationManager::CanStartAndStopInterfaces);

  // Is there default access point, use it
  QNetworkConfiguration cfg1 = manager.defaultConfiguration();
  if (!cfg1.isValid() || (!canStartIAP && cfg1.state() != QNetworkConfiguration::Active)) {
    networkSetupError = 
        QString(tr("This example requires networking, "
                   "and no avaliable networks or access points "
                    "could be found."));
    QTimer::singleShot(0, this, SLOT(networkSetupError()));
    return;
  }

  netSession = new QNetworkSession(cfg1, this);
  conHelp = new ConnectivityHelper (netSession, this);
  connect (netSession, SIGNAL (opened()),
           this, SLOT (networkSessionOpened ()));
  connect (conHelp, SIGNAL (networkingCancelled()),
           this, SLOT (Quit()));
}
Ejemplo n.º 7
0
bool TCPClientProducer::init()
{
    assert( m_networkSession == 0 );
    assert( m_tcpSocket != 0 );

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered)
        {
            config = manager.defaultConfiguration();
        }

        m_networkSession = new QNetworkSession(config);
        connect(m_networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        qDebug() << "Opening network session.";
        m_networkSession->open();
    }
    return true;
}
Ejemplo n.º 8
0
ResourceManager::ResourceManager(QObject *parent)
    : QObject(parent)
    , mPathsLoaded(false)
    , mResourceListModel(new ResourceListModel(this))
{
    // TODO: This takes about 400 ms on my system. Doing it here prevents
    // experiencing this hickup later on when the the network access manager is
    // used for the first time. Even on startup it's ugly though, so hopefully
    // there's a way to avoid it completely...
    QNetworkConfigurationManager manager;
    mNetworkAccessManager.setConfiguration(manager.defaultConfiguration());

    // Use a disk cache to avoid re-downloading data all the time
#if QT_VERSION >= 0x050000
    QString cacheLocation =
            QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
#else
    QString cacheLocation =
            QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
#endif

    if (!cacheLocation.isEmpty()) {
        cacheLocation += QLatin1String("/httpCache");

        QNetworkDiskCache *diskCache = new QNetworkDiskCache(this);
        diskCache->setCacheDirectory(cacheLocation);
        mNetworkAccessManager.setCache(diskCache);
    } else {
        qWarning() << "CacheLocation is not supported on this platform, "
                      "no disk cache is used!";
    }

    Q_ASSERT(!mInstance);
    mInstance = this;
}
Ejemplo n.º 9
0
Client::Client(QString purpose) : networkSession(0)
{
    Client::purpose = purpose;
    tcpSocket = new QTcpSocket;
    Client::blockSize = 0;
    qDebug() << connect(tcpSocket, &QTcpSocket::readyRead, this, &Client::readData);
    //connect(tcpSocket, &QTcpSocket::error, this, &Client::displayError);

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        qDebug() << connect(networkSession, &QNetworkSession::opened, this, &Client::sessionOpened);
    }
    qDebug() << "Client set up, waiting";
}
Ejemplo n.º 10
0
Server::Server(QObject *parent) :
    QObject(parent), tcpServer(0), networkSession(0), memBuf(NULL)
{
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        QTextStream out(stdout);
        out << tr("Opening network session.");

        networkSession->open();
    } else {
        sessionOpened();
    }

    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendImage()));
}
Ejemplo n.º 11
0
bool Network::openConnection(QString &netInterface)
{
    // Internet Access Point
    QNetworkConfigurationManager manager;

    const bool canStartIAP = (manager.capabilities()
        & QNetworkConfigurationManager::CanStartAndStopInterfaces);

    // If there is a default access point, use it
    QNetworkConfiguration cfg = manager.defaultConfiguration();

    if (!cfg.isValid() || !canStartIAP) {
        return false;
    }

    // Open session
    m_session = new QNetworkSession(cfg);
    m_session->open();
    // Waits for session to be open and continues after that
    m_session->waitForOpened();

    // Show interface name to the user
    QNetworkInterface iff = m_session->interface();
    netInterface = iff.humanReadableName();
    return true;
}
Ejemplo n.º 12
0
Server::Server(QWidget *parent) :
	QDialog(parent),
	mTcpServer(0),
	mNetworkSession(0) {
	QNetworkConfigurationManager manager;
	if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
		// Get saved network configuration
		QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
		settings.beginGroup(QLatin1String("QtNetwork"));
		const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
		settings.endGroup();

		// If the saved network configuration is not currently discovered use the system default
		QNetworkConfiguration config = manager.configurationFromIdentifier(id);
		if ((config.state() & QNetworkConfiguration::Discovered) != QNetworkConfiguration::Discovered) {
			config = manager.defaultConfiguration();
		}

		mNetworkSession = new QNetworkSession(config, this);
		connect(mNetworkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

		mNetworkSession->open();
	} else {
		sessionOpened();
	}

	mIPAddressMapper = new QSignalMapper;
	connect(mTcpServer, SIGNAL(newConnection()), this, SLOT(acceptClientConnection()));
	connect(mIPAddressMapper, SIGNAL(mapped(QString)), this, SIGNAL(clientDisconnected(QString)));
}
Ejemplo n.º 13
0
Server::Server()
{
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) != QNetworkConfiguration::Discovered)
        {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        if (networkSession)
        {
            connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

            TRACE_INFO(NET, "Opening network session...\n");
            networkSession->open();
        }
    }
    else
    {
        sessionOpened();
    }

        fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
                 << tr("You've got to think about tomorrow.")
                 << tr("You will be surprised by a loud noise.")
                 << tr("You will feel hungry again in another hour.")
                 << tr("You might have mail.")
                 << tr("You cannot kill time without injuring eternity.")
                 << tr("Computers are not intelligent. They only think they are.");

        if (tcpServer)
        {
            connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendDatas()));
        }
/*
        connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

        QHBoxLayout *buttonLayout = new QHBoxLayout;
        buttonLayout->addStretch(1);
        buttonLayout->addWidget(quitButton);
        buttonLayout->addStretch(1);

        QVBoxLayout *mainLayout = new QVBoxLayout;
        mainLayout->addWidget(statusLabel);
        mainLayout->addLayout(buttonLayout);
        setLayout(mainLayout);

        setWindowTitle(tr("Fortune Server"));
*/
}
Ejemplo n.º 14
0
void Server::StartServer()
{
    shotTimer->stop();
    is_config_mode = false;
    emit write_message(tr("Network session starting."));

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpen()));

        emit write_message(tr("Opening network session."));
        networkSession->open();
    } else {
        sessionOpen();
    }

    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(recieveConnection()));
}
BigBlobbyClient::BigBlobbyClient() :
  networkSession_( NULL ),
  tcpSocket_( new QTcpSocket( this ) ),
  portNumber_( DEFAULT_PORT_NUMBER ),
  log_( logger::FileLogger::instance() )
{
    connect( tcpSocket_, SIGNAL( readyRead() ), this, SLOT( readBigBlobbyResponse() ) );
    connect( tcpSocket_, SIGNAL( error( QAbstractSocket::SocketError ) ),
             this, SLOT( displayError( QAbstractSocket::SocketError ) ) );

    QNetworkConfigurationManager manager;

    if( manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired ) {
        // Get saved network configuration
        QSettings settings( QSettings::UserScope, QLatin1String( "BigBlobby" ) );
        settings.beginGroup( QLatin1String( "QtNetwork" ) );
        const QString id = settings.value( QLatin1String( "DefaultNetworkConfiguration" ) ).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier( id );

        if( (config.state() & QNetworkConfiguration::Discovered) != QNetworkConfiguration::Discovered ) {
            config = manager.defaultConfiguration();
        }
        networkSession_ = new QNetworkSession( config, this );
        connect( networkSession_, SIGNAL( opened() ), this, SLOT( sessionOpened() ) );
        networkSession_->open();
    }
}
Ejemplo n.º 16
0
Server::Server(QWidget *parent) :
    QDialog(parent), tcpServer(0), clientSocket(0), networkSession(0),
    blockSize(0)
{
    serverStatusLabel = new QLabel(tr("Status"));
    messageLabel = new QLabel(tr("Message:"));
    quitButton = new QPushButton(tr("Quit"));
    quitButton->setAutoDefault(false);
    sendMessageButton = new QPushButton(tr("Send Message"));

    chatBox = new QTextEdit;
    chatBox->setReadOnly(true);

    messageLineEdit = new QLineEdit;
    messageLineEdit->setEnabled(false);

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) != QNetworkConfiguration::Discovered)
        {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        serverStatusLabel->setText("Opening network session.");
        networkSession->open();
    }
    else
        sessionOpened();


    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(serverStatusLabel, 0, 0);
    mainLayout->addWidget(messageLabel, 2, 0);
    mainLayout->addWidget(messageLineEdit, 3, 0);
    mainLayout->addWidget(sendMessageButton, 4, 0);
    mainLayout->addWidget(chatBox, 5, 0);
    mainLayout->addWidget(quitButton, 6, 0, 1, 2);
    setLayout(mainLayout);


    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(sendMessageButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(clientProcessing()));

    setWindowTitle("Server");
}
Ejemplo n.º 17
0
void tst_qnetworkconfiguration::bearerType()
{
    QNetworkConfigurationManager m;
    QList<QNetworkConfiguration> allConfs = m.allConfigurations();
    QElapsedTimer timer;
    for (int a = 0; a < allConfs.count(); a++) {
        timer.start();
        QNetworkConfiguration::BearerType type = allConfs.at(a).bearerType();
        qint64 elapsed = timer.elapsed();
        QString typeString;
        switch (type) {
        case QNetworkConfiguration::BearerUnknown:
            typeString = QLatin1String("Unknown");
            break;
        case QNetworkConfiguration::BearerEthernet:
            typeString = QLatin1String("Ethernet");
            break;
        case QNetworkConfiguration::BearerWLAN:
            typeString = QLatin1String("WLAN");
            break;
        case QNetworkConfiguration::Bearer2G:
            typeString = QLatin1String("2G");
            break;
        case QNetworkConfiguration::BearerCDMA2000:
            typeString = QLatin1String("CDMA2000");
            break;
        case QNetworkConfiguration::BearerWCDMA:
            typeString = QLatin1String("WCDMA");
            break;
        case QNetworkConfiguration::BearerHSPA:
            typeString = QLatin1String("HSPA");
            break;
        case QNetworkConfiguration::BearerBluetooth:
            typeString = QLatin1String("Bluetooth");
            break;
        case QNetworkConfiguration::BearerWiMAX:
            typeString = QLatin1String("WiMAX");
            break;
        case QNetworkConfiguration::BearerEVDO:
            typeString = QLatin1String("EVDO");
            break;
        case QNetworkConfiguration::BearerLTE:
            typeString = QLatin1String("LTE");
            break;
        default:
            typeString = "unknown bearer (?)";
        }

        const char *isDefault = (allConfs.at(a) == m.defaultConfiguration())
                ? "*DEFAULT*" : "";
        qDebug() << isDefault << "identifier:" << allConfs.at(a).identifier()
                 << "bearer type name:" << allConfs.at(a).bearerTypeName()
                 << "bearer type:" << type << "(" << typeString << ")"
                 << "elapsed:" << elapsed;
        QCOMPARE(allConfs.at(a).bearerTypeName(), typeString);
    }
}
NetworkSessionManagerPrivate::NetworkSessionManagerPrivate(NetworkSessionManager *parent)
    : q_ptr(parent),
      networkSession(0),
#ifdef __ARMEL__
      isSessionReady(false)
#else
      isSessionReady(true)
#endif
{}

NetworkSessionManagerPrivate::~NetworkSessionManagerPrivate()
{
    if (networkSession)
        delete networkSession;
}

void NetworkSessionManagerPrivate::startSession()
{
    Q_Q(NetworkSessionManager);

#ifndef __ARMEL__
    emit q->sessionReady();
    return;
#endif

    if (networkSession && !isSessionReady) {
        networkSession->open();
    } else {

        QNetworkConfigurationManager manager;
        QNetworkConfiguration cfg = manager.defaultConfiguration();

        if (!cfg.isValid()) {
            QLatin1String msg("Network configuration manager -"
                          "invalid default configuration");
            qWarning() << msg;
            emit q->error(NetworkSessionManager::Configuration);
            return;
        }

        if (networkSession == 0) {
            networkSession = new QNetworkSession(cfg);

            connect(networkSession,
                    SIGNAL(error(QNetworkSession::SessionError)),
                    SLOT(sessionErrorHandler(QNetworkSession::SessionError)));
            connect(networkSession,
                    SIGNAL(stateChanged(QNetworkSession::State)),
                    SLOT(sessionStateHandler(QNetworkSession::State)));
            connect(networkSession, SIGNAL(opened()), SLOT(sessionOpened()));
        }

        // pops up connectivity if needed
        networkSession->open();
    }
}
Ejemplo n.º 19
0
Server::Server(/*  QWidget *parent  */)
:   /*QDialog(parent),*/ tcpServer(0), networkSession(0)
{
    //statusLabel = new QLabel;
    //quitButton = new QPushButton(tr("Quit"));
    //quitButton->setAutoDefault(false);

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        ///statusLabel->setText(tr("Opening network session."));
        std::cout << "Opening network session." << std::endl;

        networkSession->open();
    } else {
        sessionOpened();
    }

        fortunes << tr("bla bla bue ee ee e e.")
                 << tr("You've got to think about tomorrow.")
                 << tr("You wi Q_OBJECTll be surprised by a loud noise.")
                 << tr("You will feel hungry again in another hour.")
                 << tr("You might have mail.")
                 << tr("You cannot kill time without injuring eternity.")
                 << tr("Computers are not intelligent. They only think they are.");

        ///connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
        connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));

//        QHBoxLayout *buttonLayout = new QHBoxLayout;
//        buttonLayout->addStretch(1);
//        buttonLayout->addWidget(quitButton);
//        buttonLayout->addStretch(1);

//        QVBoxLayout *mainLayout = new QVBoxLayout;
//        mainLayout->addWidget(statusLabel);
//        mainLayout->addLayout(buttonLayout);
//        setLayout(mainLayout);

//        setWindowTitle(tr("Fortune Server"));
}
Ejemplo n.º 20
0
MapZoom::MapZoom()
    : QMainWindow(0)
{
    map = new LightMaps(this);
    setCentralWidget(map);
    map->setFocus();

    QAction *osloAction = new QAction(tr("&Oslo"), this);
    QAction *berlinAction = new QAction(tr("&Berlin"), this);
    QAction *jakartaAction = new QAction(tr("&Jakarta"), this);
    QAction *nightModeAction = new QAction(tr("Night Mode"), this);
    nightModeAction->setCheckable(true);
    nightModeAction->setChecked(false);
    QAction *osmAction = new QAction(tr("About OpenStreetMap"), this);
    connect(osloAction, SIGNAL(triggered()), SLOT(chooseOslo()));
    connect(berlinAction, SIGNAL(triggered()), SLOT(chooseBerlin()));
    connect(jakartaAction, SIGNAL(triggered()), SLOT(chooseJakarta()));
    connect(nightModeAction, SIGNAL(triggered()), map, SLOT(toggleNightMode()));
    connect(osmAction, SIGNAL(triggered()), SLOT(aboutOsm()));

    QMenu *menu = menuBar()->addMenu(tr("&Options"));
    menu->addAction(osloAction);
    menu->addAction(berlinAction);
    menu->addAction(jakartaAction);
    menu->addSeparator();
    menu->addAction(nightModeAction);
    menu->addAction(osmAction);

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id =
            settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system
        // default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        networkSession->open();
    } else {
        networkSession = 0;
    }

    setWindowTitle(tr("Light Maps"));
}
Ejemplo n.º 21
0
RSSListing::RSSListing(QWidget *parent)
    : QWidget(parent), currentReply(0)
{
#ifdef Q_OS_SYMBIAN
    // Set Internet Access Point
    QNetworkConfigurationManager manager;
    const bool canStartIAP = manager.capabilities() & QNetworkConfigurationManager::CanStartAndStopInterfaces;

    // Is there default access point, use it
    QNetworkConfiguration cfg = manager.defaultConfiguration();
    if (!cfg.isValid() || !canStartIAP) {
        // Available Access Points not found
        QMessageBox::warning(this, "Error", "No access point");
        return;
    }

    m_session = new QNetworkSession(cfg);
    m_session->open();
    m_session->waitForOpened();
#endif

    lineEdit = new QLineEdit(this);
    lineEdit->setText("http://labs.qt.nokia.com/blogs/feed");

    fetchButton = new QPushButton(tr("Fetch"), this);

    treeWidget = new QTreeWidget(this);
    connect(treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
            this, SLOT(itemActivated(QTreeWidgetItem*)));
    QStringList headerLabels;
    headerLabels << tr("Title") << tr("Link");
    treeWidget->setHeaderLabels(headerLabels);
    treeWidget->header()->setResizeMode(QHeaderView::ResizeToContents);

    connect(&manager, SIGNAL(finished(QNetworkReply*)),
             this, SLOT(finished(QNetworkReply*)));

    connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(fetch()));
    connect(fetchButton, SIGNAL(clicked()), this, SLOT(fetch()));

    QVBoxLayout *layout = new QVBoxLayout(this);

    QHBoxLayout *hboxLayout = new QHBoxLayout;

    hboxLayout->addWidget(lineEdit);
    hboxLayout->addWidget(fetchButton);

    layout->addLayout(hboxLayout);
    layout->addWidget(treeWidget);

    setWindowTitle(tr("RSS listing example"));
#if !defined(Q_OS_SYMBIAN) && !defined(Q_WS_MAEMO_5)
    resize(640,480);
#endif
}
Ejemplo n.º 22
0
void FtpClient::init()
{
    qDebug() << "FtpClient:: " << port << " Init";
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

    qDebug() << "FtpClient:: " << port << " Init connect";
    // from abtractsocket
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(handleError(QAbstractSocket::SocketError)));
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(handleConnected()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(handleDisconnected()));
    connect(tcpSocket, SIGNAL(hostFound()), this, SLOT(handleHostFound()));
    connect(tcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy&,QAuthenticator*)), this, SLOT(handleProxyAuthenticationRequired(const QNetworkProxy&,QAuthenticator*)));
    connect(tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(handleStateChanged(QAbstractSocket::SocketState)));
    // from QIODevice
    connect(tcpSocket, SIGNAL(aboutToClose()), this, SLOT(handleAboutToClose()));
    connect(tcpSocket, SIGNAL(bytesWritten(qint64)), this, SLOT(handleBytesWritten(qint64)));
    connect(tcpSocket, SIGNAL(readChannelFinished()), this, SLOT(handleReadChannelFinished()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(handleReadyRead()));


    qDebug() << "FtpClient:: " << port << " Init NetworkConfigurationManager manager";
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        qDebug() << "FtpClient::Init QNetworkConfigurationManager::NetworkSessionRequired";
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String(SETTING_STR));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        qDebug() << "FtpClient:: " << port << " Init new QNetworkSession(config, this)";
        networkSession = new QNetworkSession(config, this);
        qDebug() << "FtpClient:: " << port << " Init connect(networkSession, SIGNAL(opened()), this, SLOT(handleSessionOpened()))";
        connect(networkSession, SIGNAL(opened()), this, SLOT(handleSessionOpened()));

        qDebug() << "FtpClient:: " << port << " Init networkSession->open()";
        networkSession->open();
    } else {
        qDebug() << "FtpClient:: Init " << port << " tcpSocket->connectToHost())" << " ipAddress " << ipAddress << " port " << port;
        tcpSocket->connectToHost(QHostAddress(ipAddress),  port);
    }

    mInitiated = true;
}
Ejemplo n.º 23
0
bool Session::ensureNetwork()
{
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        if (!s_network)
            s_network = new QNetworkSession(manager.defaultConfiguration(), qApp);
        s_network->open();
    }
    // TODO: return value?
    return true;
}
Ejemplo n.º 24
0
void GuiBehind::initConnection()
{
    // Connection
    QNetworkConfigurationManager manager;
    const bool canStartIAP = (manager.capabilities() & QNetworkConfigurationManager::CanStartAndStopInterfaces);
    QNetworkConfiguration cfg = manager.defaultConfiguration();
    if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) return;
    mNetworkSession = new QNetworkSession(cfg, this);
    connect(mNetworkSession, SIGNAL(opened()), this, SLOT(connectOpened()));
    connect(mNetworkSession, SIGNAL(error(QNetworkSession::SessionError)), this, SLOT(connectError(QNetworkSession::SessionError)));
    mNetworkSession->open();
}
Ejemplo n.º 25
0
 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);

     QNetworkConfigurationManager manager;
     if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
         // Get saved network configuration
         QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
         settings.beginGroup(QLatin1String("QtNetwork"));
         const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
         settings.endGroup();

         // If the saved network configuration is not currently discovered use the system default
         QNetworkConfiguration config = manager.configurationFromIdentifier(id);
         if ((config.state() & QNetworkConfiguration::Discovered) !=
             QNetworkConfiguration::Discovered) {
             config = manager.defaultConfiguration();
         }

         QNetworkSession *networkSession = new QNetworkSession(config, &app);
         networkSession->open();
         networkSession->waitForOpened();

         if (networkSession->isOpen()) {
             // Save the used configuration
             QNetworkConfiguration config = networkSession->configuration();
             QString id;
             if (config.type() == QNetworkConfiguration::UserChoice) {
                 id = networkSession->sessionProperty(
                         QLatin1String("UserChoiceConfiguration")).toString();
             } else {
                 id = config.identifier();
             }

             QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
             settings.beginGroup(QLatin1String("QtNetwork"));
             settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
             settings.endGroup();
         }
     }

     //ChatDialog dialog;
     InitialWindow window;

 #ifdef Q_OS_SYMBIAN
     // Make application better looking and more usable on small screen
    // dialog.showMaximized();
 #else
  //   dialog.show();
     window.show();
 #endif
     return app.exec();
 }
void tst_QNetworkConfiguration::comparison()
{
    //test copy constructor and assignment operator
    //compare invalid connection points
    QNetworkConfiguration pt1;
    QVERIFY(!pt1.isValid());
    QVERIFY(pt1.type() == QNetworkConfiguration::Invalid);

    QNetworkConfiguration pt2(pt1);
    QVERIFY(pt1==pt2);
    QVERIFY(!(pt1!=pt2));
    QVERIFY(pt1.name() == pt2.name());
    QVERIFY(pt1.isValid() == pt2.isValid());
    QVERIFY(pt1.type() == pt2.type());
    QVERIFY(pt1.state() == pt2.state());
    QVERIFY(pt1.purpose() == pt2.purpose());


    QNetworkConfiguration pt3;
    pt3 = pt1;
    QVERIFY(pt1==pt3);
    QVERIFY(!(pt1!=pt3));
    QVERIFY(pt1.name() == pt3.name());
    QVERIFY(pt1.isValid() == pt3.isValid());
    QVERIFY(pt1.type() == pt3.type());
    QVERIFY(pt1.state() == pt3.state());
    QVERIFY(pt1.purpose() == pt3.purpose());

    //test case must run on machine that has valid connection points
    QNetworkConfigurationManager manager;
    QList<QNetworkConfiguration> preScanConfigs = manager.allConfigurations();

    QSignalSpy spy(&manager, SIGNAL(updateCompleted()));
    manager.updateConfigurations(); //initiate scans
    QTRY_VERIFY_WITH_TIMEOUT(spy.count() == 1, TestTimeOut); //wait for scan to complete

    QList<QNetworkConfiguration> configs = manager.allConfigurations(QNetworkConfiguration::Discovered);
    QVERIFY(configs.count());
    QNetworkConfiguration defaultConfig = manager.defaultConfiguration();
    QVERIFY(defaultConfig.isValid());
    QVERIFY(defaultConfig.type() != QNetworkConfiguration::Invalid);
    QVERIFY(!defaultConfig.name().isEmpty());

    pt3 = defaultConfig;
    QVERIFY(defaultConfig==pt3);
    QVERIFY(!(defaultConfig!=pt3));
    QVERIFY(defaultConfig.name() == pt3.name());
    QVERIFY(defaultConfig.isValid() == pt3.isValid());
    QVERIFY(defaultConfig.type() == pt3.type());
    QVERIFY(defaultConfig.state() == pt3.state());
    QVERIFY(defaultConfig.purpose() == pt3.purpose());
}
Ejemplo n.º 27
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QNetworkConfigurationManager manager;
        if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
            // Get saved network configuration
            QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
            settings.beginGroup(QLatin1String("QtNetwork"));
            const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
            settings.endGroup();

            // If the saved network configuration is not currently discovered use the system default
            QNetworkConfiguration config = manager.configurationFromIdentifier(id);
            if ((config.state() & QNetworkConfiguration::Discovered) !=
                QNetworkConfiguration::Discovered) {
                config = manager.defaultConfiguration();
            }

            QNetworkSession *networkSession = new QNetworkSession(config, &a);
            networkSession->open();
            networkSession->waitForOpened();

            if (networkSession->isOpen()) {
                // Save the used configuration
                QNetworkConfiguration config = networkSession->configuration();
                QString id;
                if (config.type() == QNetworkConfiguration::UserChoice) {
                    id = networkSession->sessionProperty(
                            QLatin1String("UserChoiceConfiguration")).toString();
                } else {
                    id = config.identifier();
                }

                QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
                settings.beginGroup(QLatin1String("QtNetwork"));
                settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
                settings.endGroup();
            }
        }





    interface w;
    w.show();

    return a.exec();
}
Ejemplo n.º 28
0
Server::Server(QWidget *parent)
:   QDialog(parent), tcpServer(0), networkSession(0)
{
    statusLabel = new QLabel;
    quitButton = new QPushButton(tr("Quit"));
    quitButton->setAutoDefault(false);

    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered) {
            config = manager.defaultConfiguration();
        }

        networkSession = new QNetworkSession(config, this);
        connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

        statusLabel->setText(tr("Opening network session."));
        networkSession->open();
    } else {
        sessionOpened();
    }

        fortunes << tr("all in on this");


        connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
        connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));

        QHBoxLayout *buttonLayout = new QHBoxLayout;
        buttonLayout->addStretch(1);
        buttonLayout->addWidget(quitButton);
        buttonLayout->addStretch(1);

        QVBoxLayout *mainLayout = new QVBoxLayout;
        mainLayout->addWidget(statusLabel);
        mainLayout->addLayout(buttonLayout);
        setLayout(mainLayout);

        setWindowTitle(tr("Fortune Server"));
}
Ejemplo n.º 29
0
TCP_Song::TCP_Song(void)
{
    // find out name of this machine
    QString name = QHostInfo::localHostName();
    if (!name.isEmpty())
    {
        qDebug() << name << endl;
    }
     // find out IP addresses of this machine
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // add non-localhost addresses
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (!ipAddressesList.at(i).isLoopback())
                  qDebug() << ipAddressesList.at(i).toString() << endl;
    }

    tcpSocket = new QTcpSocket(this);



    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readSongs()));
    QNetworkConfigurationManager manager;
    if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired)
    {
        // Get saved network configuration
        QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
        settings.beginGroup(QLatin1String("QtNetwork"));
        const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
        settings.endGroup();

        // If the saved network configuration is not currently discovered use the system default
        QNetworkConfiguration config = manager.configurationFromIdentifier(id);
        if ((config.state() & QNetworkConfiguration::Discovered) !=
            QNetworkConfiguration::Discovered)
        {
            config = manager.defaultConfiguration();
        }

         networkSession = new QNetworkSession(config, this);
         connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

         networkSession->open();
    }

}
Ejemplo n.º 30
0
MainWindow::MainWindow(const QVariantHash &programOptions, QWidget *parent)
    : QMainWindow(parent),
    m_programOptions(programOptions)
{
    // Set Internet Access Point
    QNetworkConfigurationManager manager;
    const bool canStartIAP = (manager.capabilities()
                              & QNetworkConfigurationManager::CanStartAndStopInterfaces);
    // Is there default access point, use it
    QNetworkConfiguration cfg = manager.defaultConfiguration();
    if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) {
        QMessageBox::information(0, tr("Map Viewer Demo"), tr(
                                     "Available Access Points not found."));
        qApp->quit();
        return;
    }

    bool open_session = true;

    if (m_programOptions.contains("session"))
        open_session = m_programOptions["session"].toBool();
    else if (m_programOptions.contains("nosession"))
        open_session = !m_programOptions["nosession"].toBool();

    if (open_session) {
        m_session = new QNetworkSession(cfg, this);

        connect(m_session, SIGNAL(opened()), this, SLOT(networkSessionOpened()));
        connect(m_session,
                SIGNAL(error(QNetworkSession::SessionError)),
                this,
                SLOT(networkSessionError(QNetworkSession::SessionError)));

        m_session->open();
    }
    else {
        qDebug("Bypassing session...");
        networkSessionOpened();
    }

    setWindowTitle("MapViewer");

    resize(640, 480);
}