На этом завершается рассмотрение класса
01 int main(int argc, char *argv[])
02 {
03 QApplication app(argc, argv);
04 TripPlanner tripPlanner;
05 tripPlanner.show;
06 return app.exec;
07 }
Теперь давайте реализуем сервер. Сервер состоит из двух классов:
01 class TripServer : public QTcpServer
02 {
03 Q_OBJECT
04 public:
05 TripServer(QObject *parent = 0);
06 private:
07 void incomingConnection(int socketId);
08 };
Класс
01 TripServer::TripServer(QObject *parent)
02 : QTcpServer (parent)
03 {
04 }
Конструктор
01 void TripServer::incomingConnection(int socketId)
02 {
03 ClientSocket *socket = new ClientSocket(this);
04 socket->setSocketDescriptor(socketId);
05 }
В функции
01 class ClientSocket : public QTcpSocket
02 {
03 Q_OBJECT
04 public:
05 ClientSocket(QObject *parent = 0);
06 private slots:
07 void readClient;
08 private:
09 void generateRandomTrip(const QString &from, const QString &to,
10 const QDate &date, const QTime &time);
11 quint16 nextBlockSize;
12 };
Класс
01 ClientSocket::ClientSocket(QObject *parent)
02 : QTcpSocket(parent)
03 {
04 connect(this, SIGNAL(readyRead), this, SLOT(readClient));
05 connect(this, SIGNAL(disconnected), this, SLOT(deleteLater));
06 nextBlockSize = 0;
07 }
В конструкторе мы устанавливаем необходимые соединения сигнал—слот и задаем переменной
Сигнал
01 void ClientSocket::readClient
02 {
03 QDataStream in(this);
04 in.setVersion(QDataStream::Qt_4_1);
05 if (nextBlockSize == 0) {
06 if (bytesAvailable < sizeof(quint16))
07 return;
08 in >> nextBlockSize;
09 }
10 if (bytesAvailable < nextBlockSize)
11 return;
12 quint8 requestType;
13 QString from;
14 QString to;
15 QDate date;
16 QTime time;
17 quint8 flag;
18 in >> requestType;
19 if (requestType == 'S') {