IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

Fortune Server Example

Demonstrates how to create a server for a network service.

Article lu   fois.

L'auteur

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

Fortune Server Example▲

This example is intended to be run alongside the https:// example or the https://.

Screenshot of the Fortune Server example

It uses https:// to accept incoming TCP connections, and a simple https:// based data transfer protocol to write a fortune to the connecting client (from the https:// example), before closing the connection.

 
Sélectionnez
class Server : public QDialog
{
    Q_OBJECT

public:
    explicit Server(QWidget *parent = nullptr);

private slots:
    void sessionOpened();
    void sendFortune();

private:
    QLabel *statusLabel = nullptr;
    QTcpServer *tcpServer = nullptr;
    QVector<QString> fortunes;
    QNetworkSession *networkSession = nullptr;
};

The server is implemented using a simple class with only one slot, for handling incoming connections.

 
Sélectionnez
    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()));

In its constructor, our Server object calls https://() to set up a https:// to listen on all addresses, on an arbitrary port. In then displays the port https:// picked in a label, so that user knows which port the fortune client should connect to.

 
Sélectionnez
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.");

Our server generates a list of random fortunes that it can send to connecting clients.

 
Sélectionnez
connect(tcpServer, &QTcpServer::newConnection, this, &Server::sendFortune);

When a client connects to our server, https:// will emit https://(). In turn, this will invoke our sendFortune() slot:

 
Sélectionnez
void Server::sendFortune()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_10);

    out << fortunes[QRandomGenerator::global()->bounded(fortunes.size())];

The purpose of this slot is to select a random line from our list of fortunes, encode it into a https:// using https://, and then write it to the connecting socket. This is a common way to transfer binary data using https://. First we create a https:// and a https:// object, passing the bytearray to https://'s constructor. We then explicitly set the protocol version of https:// to https:// to ensure that we can communicate with clients from future versions of Qt (see https://()). We continue by streaming in a random fortune.

 
Sélectionnez
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, &QAbstractSocket::disconnected,
            clientConnection, &QObject::deleteLater);

We then call https://(), which returns the https:// representing the server side of the connection. By connecting https://() to https://(), we ensure that the socket will be deleted after disconnecting.

 
Sélectionnez
    clientConnection->write(block);
    clientConnection->disconnectFromHost();
}

The encoded fortune is written using https://(), and we finally call https://(), which will close the connection after https:// has finished writing the fortune to the network. Because https:// works asynchronously, the data will be written after this function returns, and control goes back to Qt's event loop. The socket will then close, which in turn will cause https://() to delete it.

List of Files▲

Files:

List of Files▲

  • fortuneserver/fortuneserver.pro

  • fortuneserver/main.cpp

  • fortuneserver/server.cpp

  • fortuneserver/server.h

See Also▲

See also https://, https://

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+   

Ce document est disponible sous la licence https:// telle que publiée par la Free Software Foundation.