[완료] Qt 네트워크 프로그래밍 질문 좀 드릴게요~

pogusm의 이미지

main.cpp

#include <QApplication>
#include <QtCore>
 
#include <stdlib.h>
 
#include "server.h"
 
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Server server;
#ifdef Q_OS_SYMBIAN
    server.showMaximized();
#else
    server.show();
#endif
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    return server.exec();
}

server.h

#ifndef SERVER_H
#define SERVER_H
 
#include <QDialog>
 
QT_BEGIN_NAMESPACE
class QLabel;
class QPushButton;
class QTcpServer;
class QNetworkSession;
QT_END_NAMESPACE
 
class Server : public QDialog
{
    Q_OBJECT
 
public:
    Server(QWidget *parent = 0);
 
private slots:
    void sessionOpened();
    void sendFortune();
 
private:
    QLabel *statusLabel;
    QPushButton *quitButton;
    QTcpServer *tcpServer;
    QStringList fortunes;
    QNetworkSession *networkSession;
};
 
#endif

server.cpp

#include <QtGui>
#include <QtNetwork>
 
#include <stdlib.h>
 
#include "server.h"
 
Server::Server(QWidget *parent)
:   QDialog(parent), tcpServer(0), networkSession(0)
{
    statusLabel = new QLabel;
    quitButton = new QPushButton(tr("Quit"));
    quitButton->setAutoDefault(false);
 
    QNetworkConfigurationManager manager;  // <------------ 여기서부터 (1)
    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();
		}
 
		networkSession = new QNetworkSession(config, this);
		connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
 
		statusLabel->setText(tr("Opening network session."));
		networkSession->open();     // <------------ 여기까지 (1)
    } 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.");
 
        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"));
}
 
void Server::sessionOpened()
{
    // Save the used configuration
    if (networkSession) {   // <------------ 여기서부터 (2)
        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();
    }    // <------------ 여기까지 (2)
 
    tcpServer = new QTcpServer(this);
    if (!tcpServer->listen()) {
        QMessageBox::critical(this, tr("Fortune Server"),
                              tr("Unable to start the server: %1.")
                              .arg(tcpServer->errorString()));
        close();
        return;
    }
 
    QString ipAddress;
	QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
	// use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
    statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
                            "Run the Fortune Client example now.")
                         .arg(ipAddress).arg(tcpServer->serverPort()));
}
 
void Server::sendFortune()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
 
    out << (quint16)0;
    out << fortunes.at(qrand() % fortunes.size());
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));
 
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));
 
    clientConnection->write(block);
    clientConnection->disconnectFromHost();
}

위 소스코는 qt 샘플 예제인 "fortuneserver" 의 소스코드 입니다.
fortuneclient 와 함께 실행되며, 포츈쿠키(행운쿠키) 같은 기능을 하는 프로그램입니다.

그런데... 여기서부터~여기까지(1) , 여기서부터~여기까지(2) 라고 표시된 부분이 무엇을 하는 부분인지 잘 모르겠습니다.
실행 해보면 해당 if 문에는 진입을 하는 경우가 없던데...
어떤 경우를 대비하여 필요한 구문인지,
내부적으로 무슨일을 하는것인지 궁금합니다.

조언 부탁드립니다~
굽신굽신~

danskesb의 이미지

1번과 2번은 심비안/마에모/미고 등 모바일 OS의 네트워크 관리 방식 때문에 추가된 부분입니다. 모바일 환경의 특성 때문에 인터넷에 연결하기 위해서는 3G/Wi-Fi 등 여러 가지 방법이 있으며, 한 번 연결해 둔 것을 기억해 두었다가 다음번에 다시 불러오는 것입니다. 데스크톱 환경에서 실행한다면 건너뛰셔도 됩니다.

pogusm의 이미지

명확한 답변!
너무너무 큰 도움이 되었습니다.

감사합니다.

굽신굽신~

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.