📄 q3ftp.cpp
字号:
dtp.writeData(); } // react on new state switch ( state ) { case Begin: // ### should never happen break; case Success: // ### success handling state = Idle; // no break! case Idle: if ( dtp.hasError() ) { emit error( Q3Ftp::UnknownError, dtp.errorMessage() ); dtp.clearError(); } startNextCmd(); break; case Waiting: // ### do nothing break; case Failure: emit error( Q3Ftp::UnknownError, replyText ); state = Idle; startNextCmd(); break; }#if defined(Q3FTPPI_DEBUG)// qDebug( "Q3FtpPI state: %d [processReply() end]", state );#endif return true;}#ifndef QT_NO_TEXTCODECQ_COMPAT_EXPORT QTextCodec *qt_ftp_filename_codec = 0;#endif/* Starts next pending command. Returns false if there are no pending commands, otherwise it returns true.*/bool Q3FtpPI::startNextCmd(){ if ( waitForDtpToConnect ) // don't process any new commands until we are connected return true;#if defined(Q3FTPPI_DEBUG) if ( state != Idle ) qDebug( "Q3FtpPI startNextCmd: Internal error! Q3FtpPI called in non-Idle state %d", state );#endif if ( pendingCommands.isEmpty() ) { currentCmd.clear(); emit finished( replyText ); return false; } currentCmd = pendingCommands.first(); pendingCommands.pop_front();#if defined(Q3FTPPI_DEBUG) qDebug( "Q3FtpPI send: %s", currentCmd.left( currentCmd.length()-2 ).latin1() );#endif state = Waiting;#ifndef QT_NO_TEXTCODEC if ( qt_ftp_filename_codec ) { int len; Q3CString enc = qt_ftp_filename_codec->fromUnicode(currentCmd,len); commandSocket.writeBlock( enc.data(), len ); } else#endif { commandSocket.writeBlock( currentCmd.latin1(), currentCmd.length() ); } return true;}void Q3FtpPI::dtpConnectState( int s ){ switch ( s ) { case Q3FtpDTP::CsClosed: if ( waitForDtpToClose ) { // there is an unprocessed reply if ( processReply() ) replyText = QLatin1String(""); else return; } waitForDtpToClose = false; readyRead(); return; case Q3FtpDTP::CsConnected: waitForDtpToConnect = false; startNextCmd(); return; case Q3FtpDTP::CsHostNotFound: case Q3FtpDTP::CsConnectionRefused: emit error( Q3Ftp::ConnectionRefused, QFtp::tr( "Connection refused for data connection" ) ); startNextCmd(); return; default: return; }}/********************************************************************** * * Q3FtpPrivate * *********************************************************************/class Q3FtpPrivate{public: Q3FtpPrivate() : close_waitForStateChange(false), state( Q3Ftp::Unconnected ), error( Q3Ftp::NoError ), npWaitForLoginDone( false ) { pending.setAutoDelete( true ); } Q3FtpPI pi; Q3PtrList<Q3FtpCommand> pending; bool close_waitForStateChange; Q3Ftp::State state; Q3Ftp::Error error; QString errorString; bool npWaitForLoginDone;};static Q3PtrDict<Q3FtpPrivate> *d_ptr = 0;static void cleanup_d_ptr(){ delete d_ptr; d_ptr = 0;}static Q3FtpPrivate* d( const Q3Ftp* foo ){ if ( !d_ptr ) { d_ptr = new Q3PtrDict<Q3FtpPrivate>; d_ptr->setAutoDelete( true ); qAddPostRoutine( cleanup_d_ptr ); } Q3FtpPrivate* ret = d_ptr->find( (void*)foo ); if ( ! ret ) { ret = new Q3FtpPrivate; d_ptr->replace( (void*) foo, ret ); } return ret;}static void delete_d( const Q3Ftp* foo ){ if ( d_ptr ) d_ptr->remove( (void*) foo );}/********************************************************************** * * Q3Ftp implementation * *********************************************************************//*! \class Q3Ftp q3ftp.h \brief The Q3Ftp class provides an implementation of the FTP protocol. \compat This class provides two different interfaces: one is the QNetworkProtocol interface that allows you to use FTP through the QUrlOperator abstraction. The other is a direct interface to FTP that gives you lower-level access to the FTP protocol for finer control. Using the direct interface you can also execute arbitrary FTP commands. Don't mix the two interfaces, since the behavior is not well-defined. If you want to use Q3Ftp with the QNetworkProtocol interface, you do not use it directly, but rather through a QUrlOperator, for example: \code QUrlOperator op( "ftp://ftp.trolltech.com" ); op.listChildren(); // Asks the server to provide a directory listing \endcode This code will only work if the Q3Ftp class is registered; to register the class, you must call q3InitNetworkProtocols() before using a QUrlOperator with Q3Ftp. The rest of this descrption describes the direct interface to FTP. The class works asynchronously, so there are no blocking functions. If an operation cannot be executed immediately, the function will still return straight away and the operation will be scheduled for later execution. The results of scheduled operations are reported via signals. This approach depends on the event loop being in operation. The operations that can be scheduled (they are called "commands" in the rest of the documentation) are the following: connectToHost(), login(), close(), list(), cd(), get(), put(), remove(), mkdir(), rmdir(), rename() and rawCommand(). All of these commands return a unique identifier that allows you to keep track of the command that is currently being executed. When the execution of a command starts, the commandStarted() signal with the command's identifier is emitted. When the command is finished, the commandFinished() signal is emitted with the command's identifier and a bool that indicates whether the command finished with an error. In some cases, you might want to execute a sequence of commands, e.g. if you want to connect and login to a FTP server. This is simply achieved: \code Q3Ftp *ftp = new Q3Ftp( this ); // this is an optional QObject parent ftp->connectToHost( "ftp.trolltech.com" ); ftp->login(); \endcode In this case two FTP commands have been scheduled. When the last scheduled command has finished, a done() signal is emitted with a bool argument that tells you whether the sequence finished with an error. If an error occurs during the execution of one of the commands in a sequence of commands, all the pending commands (i.e. scheduled, but not yet executed commands) are cleared and no signals are emitted for them. Some commands, e.g. list(), emit additional signals to report their results. Example: If you want to download the INSTALL file from Trolltech's FTP server, you would write this: \code ftp->connectToHost( "ftp.trolltech.com" ); // id == 1 ftp->login(); // id == 2 ftp->cd( "qt" ); // id == 3 ftp->get( "INSTALL" ); // id == 4 ftp->close(); // id == 5 \endcode For this example the following sequence of signals is emitted (with small variations, depending on network traffic, etc.): \code start( 1 ) stateChanged( HostLookup ) stateChanged( Connecting ) stateChanged( Connected ) finished( 1, false ) start( 2 ) stateChanged( LoggedIn ) finished( 2, false ) start( 3 ) finished( 3, false ) start( 4 ) dataTransferProgress( 0, 3798 ) dataTransferProgress( 2896, 3798 ) readyRead() dataTransferProgress( 3798, 3798 ) readyRead() finished( 4, false ) start( 5 ) stateChanged( Closing ) stateChanged( Unconnected ) finished( 5, false ) done( false ) \endcode The dataTransferProgress() signal in the above example is useful if you want to show a \link QProgressBar progress bar \endlink to inform the user about the progress of the download. The readyRead() signal tells you that there is data ready to be read. The amount of data can be queried then with the bytesAvailable() function and it can be read with the readBlock() or readAll() function. If the login fails for the above example, the signals would look like this: \code start( 1 ) stateChanged( HostLookup ) stateChanged( Connecting ) stateChanged( Connected ) finished( 1, false ) start( 2 ) finished( 2, true ) done( true ) \endcode You can then get details about the error with the error() and errorString() functions. The functions currentId() and currentCommand() provide more information about the currently executing command. The functions hasPendingCommands() and clearPendingCommands() allow you to query and clear the list of pending commands. The safest and easiest way to use the FTP protocol is to use QUrlOperator() or the FTP commands described above. If you are an experienced network programmer and want to have complete control you can use rawCommand() to execute arbitrary FTP commands. \sa Q3NetworkProtocol, Q3UrlOperator Q3Http*//*! Constructs a Q3Ftp object.*/Q3Ftp::Q3Ftp() : Q3NetworkProtocol(){ init();}/*! Constructs a Q3Ftp object. The \a parent and \a name parameters are passed to the QObject constructor.*/Q3Ftp::Q3Ftp( QObject *parent, const char *name ) : Q3NetworkProtocol(){ if ( parent ) parent->insertChild( this ); setName( name ); init();}void Q3Ftp::init(){ Q3FtpPrivate *d = ::d( this ); d->errorString = QFtp::tr( "Unknown error" ); connect( &d->pi, SIGNAL(connectState(int)), SLOT(piConnectState(int)) ); connect( &d->pi, SIGNAL(finished(QString)), SLOT(piFinished(QString)) ); connect( &d->pi, SIGNAL(error(int,QString)), SLOT(piError(int,QString)) ); connect( &d->pi, SIGNAL(rawFtpReply(int,QString)), SLOT(piFtpReply(int,QString)) ); connect( &d->pi.dtp, SIGNAL(readyRead()), SIGNAL(readyRead()) ); connect( &d->pi.dtp, SIGNAL(dataTransferProgress(int,int)), SIGNAL(dataTransferProgress(int,int)) ); connect( &d->pi.dtp, SIGNAL(listInfo(QUrlInfo)), SIGNAL(listInfo(QUrlInfo)) );}/*! \enum Q3Ftp::State This enum defines the connection state: \value Unconnected There is no connection to the host. \value HostLookup A host name lookup is in progress. \value Connecting An attempt to connect to the host is in progress. \value Connected Connection to the host has been achieved. \value LoggedIn Connection and user login have been achieved. \value Closing The connection is closing down, but it is not yet closed. (The state will be \c Unconnected when the connection is closed.) \sa stateChanged() state()*//*! \enum Q3Ftp::Error This enum identifies the error that occurred. \value NoError No error occurred. \value HostNotFound The host name lookup failed. \value ConnectionRefused The server refused the connection. \value NotConnected Tried to send a command, but there is no connection to a server. \value UnknownError An error other than those specified above occurred. \sa error()*//*! \enum Q3Ftp::Command This enum is used as the return value for the currentCommand() function. This allows you to perform specific actions for particular commands, e.g. in a FTP client, you might want to clear the directory view when a list() command is started; in this case you can simply check in the slot connected to the start() signal if the currentCommand() is \c List. \value None No command is being executed. \value ConnectToHost connectToHost() is being executed. \value Login login() is being executed. \value Close close() is being executed. \value List list() is being executed. \value Cd cd() is being executed. \value Get get() is being executed. \value Put put() is being executed. \value Remove remove() is being executed. \value Mkdir mkdir() is being executed. \value Rmdir rmdir() is being executed. \value Rename rename() is being executed. \value RawCommand rawCommand() is being executed. \sa currentCommand()*//*! \fn void Q3Ftp::stateChanged( int state ) This signal is emitted when the state of the connection changes. The argument \a state is the new state of the connection; it is one of the \l State values. It is usually emitted in response to a connectToHost() or close() command, but it can also be emitted "spontaneously", e.g. when the server closes the connection unexpectedly. \sa connectToHost() close() state() State*//*! \fn void Q3Ftp::listInfo( const QUrlInfo &i ); This signal is emitted for each directory entry the list() command finds. The details of the entry are stored in \a i. \sa list()*//*! \fn void Q3Ftp::commandStarted( int id ) This signal is emitted when processing the command identified by \a id starts. \sa commandFinished() done()*//*!
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -