Exemple #1
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;
}
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;
}
Exemple #3
0
QT_USE_NAMESPACE


#define NO_DISCOVERED_CONFIGURATIONS_ERROR 1
#define SESSION_OPEN_ERROR 2


int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    // Cannot read/write to processes on WinCE or Symbian.
    // Easiest alternative is to use sockets for IPC.

    QLocalSocket oopSocket;

    oopSocket.connectToServer("tst_qnetworksession");
    oopSocket.waitForConnected(-1);

    QNetworkConfigurationManager manager;
    QList<QNetworkConfiguration> discovered =
        manager.allConfigurations(QNetworkConfiguration::Discovered);

    foreach(QNetworkConfiguration config, discovered) {
        qDebug() << "Lackey: Name of the config enumerated: " << config.name();
        qDebug() << "Lackey: State of the config enumerated: " << config.state();
    }
Exemple #4
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()));
}
Exemple #5
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"));
*/
}
Exemple #6
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);
    }
}
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();
    }
}
Exemple #8
0
static void setupNetwork(GlobalSettings *settings)
{
    QNetworkProxy proxy;
    if (settings->isEnabled(GlobalSettings::Proxy)) {
        QString proxyHost(settings->value(GlobalSettings::ProxyHost).toString());
        int proxyPort = settings->value(GlobalSettings::ProxyPort).toInt();
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(proxyHost);
        proxy.setPort(proxyPort);
        QNetworkProxy::setApplicationProxy(proxy);
        qWarning() << "Using proxy host" << proxyHost << "on port" << proxyPort;
    }

    // Set Internet Access Point
    QNetworkConfigurationManager mgr;
    QList<QNetworkConfiguration> activeConfigs = mgr.allConfigurations();
    if (activeConfigs.count() <= 0)
        return;

    QNetworkConfiguration cfg = activeConfigs.at(0);
    foreach(QNetworkConfiguration config, activeConfigs) {
        if (config.type() == QNetworkConfiguration::UserChoice) {
            cfg = config;
            break;
        }
    }

    g_networkSession = new QNetworkSession(cfg);
    g_networkSession->open();
    g_networkSession->waitForOpened(-1);
}
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";
}
Exemple #10
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)));
}
/*!
    Starts the backend.  Returns \c true if the backend is started.  Returns \c false if the backend
    could not be started due to an unopened or roaming session.  The caller should recall this
    function once the session has been opened or the roaming process has finished.
*/
bool QNetworkAccessBackend::start()
{
#ifndef QT_NO_BEARERMANAGEMENT
    // For bearer, check if session start is required
    QSharedPointer<QNetworkSession> networkSession(manager->getNetworkSession());
    if (networkSession) {
        // session required
        if (networkSession->isOpen() &&
            networkSession->state() == QNetworkSession::Connected) {
            // Session is already open and ready to use.
            // copy network session down to the backend
            setProperty("_q_networksession", QVariant::fromValue(networkSession));
        } else {
            // Session not ready, but can skip for loopback connections

            // This is not ideal.
            const QString host = reply->url.host();

            if (host == QLatin1String("localhost") ||
                QHostAddress(host).isLoopback() ||
                reply->url.isLocalFile()) {
                // Don't need an open session for localhost access.
            } else {
                // need to wait for session to be opened
                return false;
            }
        }
    }
#endif

#ifndef QT_NO_NETWORKPROXY
#ifndef QT_NO_BEARERMANAGEMENT
    // Get the proxy settings from the network session (in the case of service networks,
    // the proxy settings change depending which AP was activated)
    QNetworkSession *session = networkSession.data();
    QNetworkConfiguration config;
    if (session) {
        QNetworkConfigurationManager configManager;
        // The active configuration tells us what IAP is in use
        QVariant v = session->sessionProperty(QLatin1String("ActiveConfiguration"));
        if (v.isValid())
            config = configManager.configurationFromIdentifier(qvariant_cast<QString>(v));
        // Fallback to using the configuration if no active configuration
        if (!config.isValid())
            config = session->configuration();
        // or unspecified configuration if that is no good either
        if (!config.isValid())
            config = QNetworkConfiguration();
    }
    reply->proxyList = manager->queryProxy(QNetworkProxyQuery(config, url()));
#else // QT_NO_BEARERMANAGEMENT
    // Without bearer management, the proxy depends only on the url
    reply->proxyList = manager->queryProxy(QNetworkProxyQuery(url()));
#endif
#endif

    // now start the request
    open();
    return true;
}
Exemple #12
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()));
}
Exemple #13
0
QT_USE_NAMESPACE


#define NO_DISCOVERED_CONFIGURATIONS_ERROR 1
#define SESSION_OPEN_ERROR 2


int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

#ifndef QT_NO_BEARERMANAGEMENT
    // Update configurations so that everything is up to date for this process too.
    // Event loop is used to wait for awhile.
    QNetworkConfigurationManager manager;
    manager.updateConfigurations();
    QEventLoop iIgnoreEventLoop;
    QTimer::singleShot(3000, &iIgnoreEventLoop, SLOT(quit()));
    iIgnoreEventLoop.exec();

    QList<QNetworkConfiguration> discovered =
        manager.allConfigurations(QNetworkConfiguration::Discovered);

    foreach(QNetworkConfiguration config, discovered) {
        qDebug() << "Lackey: Name of the config enumerated: " << config.name();
        qDebug() << "Lackey: State of the config enumerated: " << config.state();
    }
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 );
}
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()));
}
Exemple #16
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();
}
/**
 * @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;
}
Exemple #18
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()));
}
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;
}
bool ConnectionTester::checkOnline()
{
    emit checkStarted(ActiveInterface);
    QNetworkConfigurationManager mgr;
    bool online = mgr.isOnline();
    emit checkFinished(ActiveInterface, online, QVariant::fromValue(online));
    return online;
}
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");
}
void tst_QNetworkConfigurationManager::allConfigurations()
{
    QNetworkConfigurationManager manager;
    QList<QNetworkConfiguration> preScanConfigs = manager.allConfigurations();

    foreach(QNetworkConfiguration c, preScanConfigs)
    {
        QVERIFY2(c.type()!=QNetworkConfiguration::UserChoice, "allConfiguration must not return UserChoice configs");
    }
Exemple #23
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();
    }
}
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"));
}
Exemple #26
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
}
Exemple #27
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"));
}
Exemple #28
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;
}
Exemple #29
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;
}
Exemple #30
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();
}