of 8
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
  Home > Articles > Programming > C/C++ This chapter is from the book C++ GUI Programming with Qt4,2nd Edition Learn More  Buy This chapter shows how to write FTPand HTTP clients, TCP client-serverapplications, and how to send andreceive UDP datagrams. 15. Networking Writing FTP ClientsWriting HTTP ClientsWriting TCP Client–Server  ApplicationsSending and Receiving UDP Datagrams Qt provides the QFtp and QHttp classes for working with FTP and HTTP. These protocols areeasy to use for downloading and uploading files and, in the case of HTTP, for sending requests to web servers and retrieving the results.Qt also provides the lower-level QTcpSocket and QUdpSocket classes, which implement the TCPand UDP transport protocols. TCP is a reliable connection-oriented protocol that operates interms of data streams transmitted between network nodes, and UDP is an unreliableconnectionless protocol based on discrete packets sent between network nodes. Both can beused to create network client and server applications. For servers, we also need the QTcpServer class to handle incoming TCP connections. Secure SSL/TLS connections can be established byusing QSslSocket instead of QTcpSocket . Writing FTP Clients The QFtp class implements the client side of the FTP protocol in Qt. It offers various functions toperform the most common FTP operations and lets us execute arbitrary FTP commands.The QFtp class works asynchronously. When we call a function such as get() or put() , it returnsimmediately and the data transfer occurs when control passes back to Qt's event loop. Thisensures that the user interface remains responsive while FTP commands are executed.We will start with an example that shows how to retrieve a single file using get() . The example isa console application called ftpget that downloads the remote file specified on the commandline. Let's begin with the main() function: int main(int argc, char *argv[]){QCoreApplication app(argc, argv);QStringList args = QCoreApplication::arguments();if (args.count() != 2) {std::cerr << Usage: ftpget url << std::endl<< Example: << std::endl<< ftpget ftp://ftp.trolltech.com/mirrors << std::endl;return 1;}FtpGet getter; C++ GUI Programming with Qt4: Networking ByJasmin BlanchetteandMark Summerfield Nov 6, 2009ContentsPrintShare ThisDiscuss Page 1 of 4 Next > Related Resources PODCASTSBLOGSARTICLESSTORE See All Related Store Items Developing Windows 8 AppsLiveLessons (Video Training),Downloadable Video: with XAML andC# By Derik Whittaker $119.99 C++ Programming Language, The, 4thEdition By Bjarne Stroustrup $47.99 SharePoint 2013 How-To By Ishai Sagi $27.99 the trusted technology learning source  View Your CartAccount Sign In Topics Store Authors Safari Books Online Imprints Explore C++ GUI Programming with Qt4: Networking | Writing ...http://www.informit.com/articles/article.aspx?p=14055521 of 806/30/2013 08:34 PM  if (!getter.getFile(QUrl(args[1])))return 1;QObject::connect(&getter, SIGNAL(done()), &app, SLOT(quit()));return app.exec();} We create a QCoreApplication rather than its subclass QApplication to avoid linking in the QtGui  library. The QCoreApplication::arguments() function returns the command-linearguments as a QStringList , with the first item being the name the program was invoked as,and any Qt-specific arguments such as -style removed. The heart of the main() function is theconstruction of the FtpGet object and the getFile() call. If the call succeeds, we let the eventloop run until the download finishes.All the work is done by the FtpGet subclass, which is defined as follows: class FtpGet : public QObject{Q_OBJECTpublic:FtpGet(QObject *parent = 0);bool getFile(const QUrl &url);signals:void done();private slots:void ftpDone(bool error);private:QFtp ftp;QFile file;}; The class has a public function, getFile() , that retrieves the file specified by a URL. The QUrl class provides a high-level interface for extracting the different parts of a URL, such as the filename, path, protocol, and port. FtpGet has a private slot, ftpDone() , that is called when the file transfer is completed, and a done() signal that it emits when the file has been downloaded. The class also has two privatevariables: the ftp variable, of type QFtp , which encapsulates the connection to an FTP server,and the file variable that is used for writing the downloaded file to disk. FtpGet::FtpGet(QObject *parent): QObject(parent){connect(&ftp, SIGNAL(done(bool)), this, SLOT(ftpDone(bool)));} In the constructor, we connect the QFtp::done(bool) signal to our ftpDone(bool) private slot. QFtp emits done(bool) when it has finished processing all requests. The bool parameterindicates whether an error occurred or not. bool FtpGet::getFile(const QUrl &url){if (!url.isValid()) {std::cerr << Error: Invalid URL << std::endl;return false;}if (url.scheme() != ftp ) {std::cerr << Error: URL must start with 'ftp:' << std::endl;return false;}if (url.path().isEmpty()) {std::cerr << Error: URL has no path << std::endl;return false;}QString localFileName = QFileInfo(url.path()).fileName();if (localFileName.isEmpty())localFileName = ftpget.out ;file.setFileName(localFileName);if (!file.open(QIODevice::WriteOnly)) {std::cerr << Error: Cannot write file C++ GUI Programming with Qt4: Networking | Writing ...http://www.informit.com/articles/article.aspx?p=14055522 of 806/30/2013 08:34 PM  << qPrintable(file.fileName()) << : << qPrintable(file.errorString()) << std::endl;return false;}ftp.connectToHost(url.host(), url.port(21));ftp.login();ftp.get(url.path(), &file);ftp.close();return true;} The getFile() function begins by checking the URL that was passed in. If a problem isencountered, the function prints an error message to cerr and returns false to indicate that thedownload failed.Instead of forcing the user to make up a local file name, we try to create a sensible name usingthe URL itself, with a fallback of ftpget.out . If we fail to open the file, we print an error messageand return false .Next, we execute a sequence of four FTP commands using our QFtp object. The url.port(21) call returns the port number specified in the URL, or port 21 if none is specified in the URL itself.Since no user name or password is given to the login() function, an anonymous login isattempted. The second argument to get() specifies the output I/O device.The FTP commands are queued and executed in Qt's event loop. The completion of all thecommands is indicated by QFtp 's done(bool) signal, which we connected to ftpDone(bool) inthe constructor. void FtpGet::ftpDone(bool error){if (error) {std::cerr << Error: << qPrintable(ftp.errorString())<< std::endl;} else {std::cerr << File downloaded as << qPrintable(file.fileName()) << std::endl;}file.close();emit done();} Once the FTP commands have been executed, we close the file and emit our own done() signal.It may appear strange that we close the file here, rather than after the ftp.close() call at theend of the getFile() function, but remember that the FTP commands are executedasynchronously and may well be in progress after the getFile() function has returned. Only when the QFtp object's done() signal is emitted do we know that the download is finished andthat it is safe to close the file. QFtp provides several FTP commands, including connectToHost() , login() , close() , list() , cd() , get() , put() , remove() , mkdir() , rmdir() , and rename() . All of these functions schedulean FTP command and return an ID number that identifies the command. It is also possible tocontrol the transfer mode (the default is passive) and the transfer type (the default is binary).Arbitrary FTP commands can be executed using rawCommand() . For example, here's how toexecute a SITE CHMOD command: ftp.rawCommand( SITE CHMOD 755 fortune );QFtp emits the commandStarted(int) signal when it starts executing a command, and it emitsthe commandFinished(int, bool) signal when the command is finished. The int parameter isthe ID number that identifies the command. If we are interested in the fate of individualcommands, we can store the ID numbers when we schedule the commands. Keeping track of theID numbers allows us to provide detailed feedback to the user. For example: bool FtpGet::getFile(const QUrl &url){...connectId = ftp.connectToHost(url.host(), url.port(21));loginId = ftp.login();getId = ftp.get(url.path(), &file);closeId = ftp.close();return true;}void FtpGet::ftpCommandStarted(int id) C++ GUI Programming with Qt4: Networking | Writing ...http://www.informit.com/articles/article.aspx?p=14055523 of 806/30/2013 08:34 PM  {if (id == connectId) {std::cerr << Connecting... << std::endl;} else if (id == loginId) {std::cerr << Logging in... << std::endl;...} Another way to provide feedback is to connect to QFtp 's stateChanged() signal, which is emitted whenever the connection enters a new state ( QFtp::Connecting , QFtp::Connected , QFtp::LoggedIn , etc.).In most applications, we are interested only in the fate of the sequence of commands as a wholerather than in particular commands. In such cases, we can simply connect to the done(bool) signal, which is emitted whenever the command queue becomes empty.When an error occurs, QFtp automatically clears the command queue. This means that if theconnection or the login fails, the commands that follow in the queue are never executed. If weschedule new commands after the error has occurred using the same QFtp object, thesecommands will be queued and executed.In the application's .pro file, we need the following line to link against the QtNetwork  library: QT += network We will now review a more advanced example. The spider command-line program downloads allthe files located in an FTP directory, recursively downloading from all the directory'ssubdirectories. The network logic is located in the Spider class: class Spider : public QObject{Q_OBJECTpublic:Spider(QObject *parent = 0);bool getDirectory(const QUrl &url);signals:void done();private slots:void ftpDone(bool error);void ftpListInfo(const QUrlInfo &urlInfo);private:void processNextDirectory();QFtp ftp;QList<QFile *> openedFiles;QString currentDir;QString currentLocalDir;QStringList pendingDirs;}; The starting directory is specified as a QUrl and is set using the getDirectory() function. Spider::Spider(QObject *parent): QObject(parent){connect(&ftp, SIGNAL(done(bool)), this, SLOT(ftpDone(bool)));connect(&ftp, SIGNAL(listInfo(const QUrlInfo &)),this, SLOT(ftpListInfo(const QUrlInfo &)));} In the constructor, we establish two signal–slot connections. The listInfo(const QUrlInfo &) signal is emitted by QFtp when we request a directory listing (in getDirectory() ) for each filethat it retrieves. This signal is connected to a slot called ftpListInfo() , which downloads the fileassociated with the URL it is given. bool Spider::getDirectory(const QUrl &url){if (!url.isValid()) {std::cerr << Error: Invalid URL << std::endl;return false;}if (url.scheme() != ftp ) {std::cerr << Error: URL must start with 'ftp:' << std::endl; C++ GUI Programming with Qt4: Networking | Writing ...http://www.informit.com/articles/article.aspx?p=14055524 of 806/30/2013 08:34 PM
Similar documents
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks