#include <QCoreApplication>#include <iostream>#include <qnetwork.h>#include <QTcpSocket>#include <QtNetwork>using namespace std;QTcpSocket *tcpSocket;qint16 port;qint16 blockSize;QString currentFortune;void requestNewFortune(){ blockSize = 0; tcpSocket->abort(); tcpSocket->connectToHost(QHostAddress::LocalHost,port);;}void readFortune(){ QDataStream in(tcpSocket); in.setVersion(QDataStream::Qt_4_0); if (blockSize == 0) { if (tcpSocket->bytesAvailable() < (int)sizeof(quint16)) return; in >> blockSize; } if (tcpSocket->bytesAvailable() < blockSize) return; QString nextFortune; in >> nextFortune; /* if (nextFortune == currentFortune) { QTimer::singleShot(0, this, SLOT(requestNewFortune())); return; } */ currentFortune = nextFortune; currentFortune="test"; // statusLabel->setText(currentFortune); // getFortuneButton->setEnabled(true);}int main(int argc, char *argv[]){ QCoreApplication app(argc, argv); currentFortune="Nothing"; cin>>port; tcpSocket = new QTcpSocket(); requestNewFortune(); readFortune(); cout<<currentFortune.toStdString()<<endl; return app.exec();}
#ifndef CLIENT_H #define CLIENT_H #include <QtNetwork> #include <QTcpSocket> #include <QObject> class QTcpSocket; class Client : public QObject { Q_OBJECT public: Client(); void start(); QString output; private slots: void requestNewFortune(); void readFortune(); private: QTcpSocket *tcpSocket; QString currentFortune; quint16 blockSize; };#endif // CLIENT_H
#include <QtNetwork>#include "client.h"#include <QTcpSocket>#include <QObject>Client::Client(){ tcpSocket = new QTcpSocket(this); QObject::connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readFortune()));}void Client::start(){ Client::requestNewFortune();}void Client::requestNewFortune(){ blockSize = 0; tcpSocket->abort(); tcpSocket->connectToHost(QHostAddress::LocalHost,54942); //<<}void Client::readFortune(){ QDataStream in(tcpSocket); in.setVersion(QDataStream::Qt_4_0); if (blockSize == 0) { if (tcpSocket->bytesAvailable() < (int)sizeof(quint16)) return; in >> blockSize; } if (tcpSocket->bytesAvailable() < blockSize) return; QString nextFortune; in >> nextFortune; currentFortune = nextFortune; output=currentFortune; //qDebug()<<output;}
#include <QCoreApplication>#include <client.h>#include <iostream>int main(int argc, char *argv[]){ QCoreApplication app(argc, argv); Client client; client.start(); qDebug()<<client.output; return app.exec();}