QTcpSocket pour un client TCP
Bonjour,
j'utilise la classe QTcpSocket pour développer un client HTTP très simple --> envoi d'une requête HTTP vers le serveur d'une centrale d'acquisitions qui me retourne un fichier XML contenant les mesures.
Ma classe Client_tcp:
client_tcp.h:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Client_tcp: public QObject
{
Q_OBJECT
public:
Client_tcp(std::string&);
bool doConnection(string&);
string get_xmlfile();
private:
string ip_serveur;
QTcpSocket* sock;
string xml_file;
private slots:
void connected();
void readyRead();
}; |
client_tcp.cpp:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
Client_tcp::Client_tcp(std::string &rq):req(rq)
{
sock = new QTcpSocket();
xml_file = "";
}
bool Client_tcp::doConnection(string& ip)
{
connect(sock, SIGNAL(connected()),this, SLOT(connected()));
connect(sock, SIGNAL(readyRead()),this, SLOT(readyRead()));
// this is not blocking call
cout << "Connect to host: " << ip.c_str() << endl;
sock->connectToHost(ip.c_str(), 80, QIODevice::ReadWrite, QAbstractSocket::IPv4Protocol);
// so we need to wait...
if(!sock->waitForConnected(2000))
{
QMessageBox msgBox;
msgBox.setText(sock->errorString());
msgBox.exec();
sock->errorString();
return false;
}
else return true;
}
void Client_tcp::connected()
{
qDebug() << "Yes!! connected";
sock->write(req.c_str(), req.size());
while(sock->waitForReadyRead(2000) == false);
}
void Client_tcp::readyRead()
{
qDebug() << "readyRead";
QByteArray buffer;
char buff[100] = {0};
qint64 nbr = sock->bytesAvailable();
cout << "nbr = " << nbr << endl;
while(sock->bytesAvailable()) {
//buffer = sock->readAll();
sock->read(buff, sizeof(buff));
buff[99] = 0;
xml_file.append(buff, sizeof(buff));
}
}
string Client_tcp::get_xmlfile()
{
return xml_file;
} |
Utilisation dans la MainWindow:
Code:
1 2 3 4 5
|
Client_tcp client(Constantes::requete);
bool retour = client.doConnection(ip);
sleep(1); //petite attente en phase de debug pour que tout ait le temps d'arriver
cout << "xml_file: " << client.get_xmlfile().c_str() << endl; |
J'ai lu et suivi pas mal d'exemples pour en arriver là et pour l'instant, ma requête est bien émise et la réponse revient du serveur (dixit Wireshark) mais je n'arrive à récupérer qu'une partie de cette réponse dans la string xml_file. Et je ne passe qu'une seule fois dans le slot Readyread().
Si quelqu'un a déjà utilisé cette classe avec succès, je prend toutes les explications.
Merci.