[완료] Qt 네트워크 프로그래밍 질문 좀 드릴게요~
글쓴이: pogusm / 작성시간: 목, 2011/12/08 - 9:46오후
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;
};
#endifserver.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 문에는 진입을 하는 경우가 없던데...
어떤 경우를 대비하여 필요한 구문인지,
내부적으로 무슨일을 하는것인지 궁금합니다.
조언 부탁드립니다~
굽신굽신~
Forums:


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