File Retrieval: Using the FTP Agent (Part I)
Example 1 uses RWFtpAgent for FTP file and directory access. The program follows these steps:
1. Creates an FTP agent object that establishes a connection with an FTP server.
2. Performs login negotiation.
3. Gets an RWSocketPortal object from the agent’s get() method.
4. Reads all data in the remote file from the socket portal.
5. Closes the data connection.
NOTE: Servers and files shown in the code might not exist and are included as examples only.
Example 1 – Retrieving a file
try {
RWFtpAgent agent("ftp.roguewave.com",
"anonymous", "me@roguewave.com"); // 1
RWSocketPortal sPortal = agent.get("remote_file"); // 2
 
RWCString packet;
while (!(packet=sPortal.recv()).isNull()) { // 3
cout << packet << endl;
}
 
bool dataClosed = agent.dataClose(); // 4
} // 5
catch (const RWxmsg& msg) { // 6
cout << "ERROR: " << msg.why() << endl;
}
//1 Constructs an RWFtpAgent object that connects to an FTP server and handles the FTP login negotiation sequence.
//2 Opens a data connection to the FTP server. The get() method automatically handles the login sequence first, then establishes a data connection with the remote server for the file transfer. The call to get() returns an IOU for an RWSocketPortal. Type conversion is used to redeem the IOU for the actual result sPortal, causing the thread to block until this result is available.
//3 Receives data on the socket portal until the recv() function returns the null string, indicating that no more data is available.
//4 Closes the data communication channel established by the get() method of RWFtpAgent in //2. The dataClose() method returns an RWTIOUResult with a redeemable bool that is immediately redeemed for the actual result dataClosed.
NOTE: The dataClose() method needs to be invoked for each data transfer session. This is because the FTP protocol establishes a new data connection for each data transfer session. The connection must be removed afterwards.
//5 Disconnects from the FTP server in the agent destructor when the agent object goes out of scope.
//6 This catch clause catches all FTP package, Networking package, and Threads Module exceptions that could be thrown from within the try block because all Rogue Wave exceptions are derived from RWxmsg. Exceptions can be thrown because of errors such as bad server connections, incorrect logins, and non-existent remote files.