Not disconnecting from FTP when NSConnection closi

2019-05-21 19:05发布

问题:

I am using an edited version of Apple's SimpleFTPSample sample code, specifically the "PUT" part. In it there is this method:

- (void)stopSendWithStatus:(NSString *)statusString
{
if (self.networkStream != nil) {
    [self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    self.networkStream.delegate = nil;
    [self.networkStream close];
    self.networkStream = nil;
}
if (self.fileStream != nil) {
    [self.fileStream close];
    self.fileStream = nil;
}
[self sendDidStopWithStatus:statusString];
uploaderbusy = 0;
}

Problem is that after the upload the application is NOT closing the connection. The code above is executed. Both IF statements are true and the code inside is executed.

This code:

    NSLog(@"%lu",[self.networkStream streamStatus]);
    [self.networkStream close];
    NSLog(@"%lu",[self.networkStream streamStatus]);

gives this output:

2013-03-03 17:50:26.460 Stockuploader[575:303] 2
2013-03-03 17:50:26.498 Stockuploader[575:303] 6

but the connection stays open and eventually times out. This is the log of the FTP server:

(000006)03/03/2013 17.50.27 - root2 (192.168.0.3)> 150 Connection accepted
(000006)03/03/2013 17.50.27 - root2 (192.168.0.3)> 226 Transfer OK
(000006)03/03/2013 17.52.28 - root2 (192.168.0.3)> 421 Connection timed out.
(000006)03/03/2013 17.52.28 - root2 (192.168.0.3)> disconnected.

Why is that?

if i CLOSE the program then the connection is instantly closed on the FTP. could it be that i have to deallocate the self.filestream? if so, how can i do it with ARC enabled?

----UPDATE----

I found that before i close the connection i have to send "QUIT" to the ftp server in order to let him know that i want to disconnect. but how can i implement the sending of "QUIT" command into the SimpleFTPSample?

回答1:

Before you open the connection, you have to set the kCFStreamPropertyFTPAttemptPersistentConnection property to FALSE:

[self.networkStream setProperty:(id)kCFBooleanFalse
                         forKey:(id)kCFStreamPropertyFTPAttemptPersistentConnection];

then the FTP stream closes both control and data connection when it is closed.

From the documentation:

kCFStreamPropertyFTPAttemptPersistentConnection
FTP Attempt Persistent Connection stream property key for set and copy operations. Set this property to kCFBooleanTrue to enable the reuse of existing server connections; set this property to kCFBooleanFalse to not reuse existing server connections. By default, this property is set to kCFBooleanTrue.



回答2:

Setting kCFStreamPropertyFTPAttemptPersistentConnection to kCFBooleanFalse did not close my lingering connection until I also set this (also prior to open):

[self.networkStream setProperty:(id)kCFBooleanTrue forKey:(id)kCFStreamPropertyShouldCloseNativeSocket];