PDA

View Full Version : GET Network program



eleanor
29th October 2007, 20:52
I'm curious, why doesn't this program work:

MAIN.CPP


#include <QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
CMainWindow window;
window.show();

//return app.exec();
}




MAINWINDOW.H


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

/**
@author eleanor <eleanor@localhost>
*/

#include <QWidget>
#include <QString>
#include <QTextStream>
#include <QTcpSocket>
#include <QAbstractSocket>
#include <QLabel>

class CMainWindow : public QWidget {
public:
CMainWindow(QWidget *parent=0);

~CMainWindow();

private:
QTcpSocket *m_pSocket;
};

#endif




MAINWINDOW.CPP


#include "mainwindow.h"

CMainWindow::CMainWindow(QWidget *parent) : QWidget(parent) {
//creating a socket
m_pSocket = new QTcpSocket(this);


QString myHost("www.google.com");
int myPort = 80;

//this function establishes connection and returns immediately
m_pSocket->connectToHost(myHost, myPort);

QString input = "GET /index.php HTTP/1.1\n\n";
if(m_pSocket->state() == QAbstractSocket::ConnectedState) {
QTextStream stream(m_pSocket);
stream << input;
}

QString text;
while(m_pSocket->canReadLine()) {
text += m_pSocket->readLine();
}

QTextStream output(stdout);
QString enteredCommand = text;
output >> text;
}


CMainWindow::~CMainWindow() {

}


I would appreciate any tips. Thanks

wysota
29th October 2007, 21:59
Because the socket works asynchronously to the application - it doesn't block when you write or read from it. You need to react on signals or use QHttp instead.

eleanor
29th October 2007, 22:08
Ok, I'm trying this way:



QString myHost("www.google.com");
int myPort = 80;

//this function establishes connection and returns immediately
m_pSocket->connectToHost(myHost, myPort);
connect(m_pSocket, SIGNAL(connected()), this, SLOT(connectedSlot()));




void CMainWindow::connectedSlot() {
QString input = "GET /index.php HTTP/1.1\n\n";
if(m_pSocket->state() == QAbstractSocket::ConnectedState) {
QTextStream stream(m_pSocket);
stream << input;
}

QString text;
while(m_pSocket->canReadLine()) {
text += m_pSocket->readLine();
}

QTextStream output(stdout);
QString enteredCommand = text;
output >> text;
}


I'm calling this slot when the connecter() signal occurs, still does not work!

wysota
30th October 2007, 08:22
Because m_pSocket->canReadLine() will return false and break out of the loop immediately - there is no data in the socket yet. You need to make your flow event driven - for example connect to the socket's readyRead() signal - it is emited when some data becomes available in the socket.