Objective c NSOutputStream完成后关闭连接
NSOutputStream发送完数据后,如何关闭连接 在四处搜索后,我发现只有在服务器断开连接时才会调用事件Objective c NSOutputStream完成后关闭连接,objective-c,cocoa,networking,stream,connection,Objective C,Cocoa,Networking,Stream,Connection,NSOutputStream发送完数据后,如何关闭连接 在四处搜索后,我发现只有在服务器断开连接时才会调用事件nsstreamventendecountered。如果OutputStream已完成要发送的数据,则不会 StreamStatus始终返回0(连接关闭)或2(连接打开),但从不返回4(写入数据) 由于上面提到的两种方法都没有充分说明写入过程,因此我无法找到一种方法来确定流是否仍在写入,或者它是否已完成,我现在可以关闭连接 经过5天的谷歌搜索和尝试,我完全失去了想法。。。谢谢你的帮助。谢
nsstreamventendecountered
。如果OutputStream已完成要发送的数据,则不会
StreamStatus
始终返回0(连接关闭)或2(连接打开),但从不返回4(写入数据)
由于上面提到的两种方法都没有充分说明写入过程,因此我无法找到一种方法来确定流是否仍在写入,或者它是否已完成,我现在可以关闭连接
经过5天的谷歌搜索和尝试,我完全失去了想法。。。谢谢你的帮助。谢谢
按要求编辑添加的代码:
- (void)startSend:(NSString *)filePath
{
BOOL success;
NSURL * url;
assert(filePath != nil);
assert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);
assert( [filePath.pathExtension isEqual:@"png"] || [filePath.pathExtension isEqual:@"jpg"] );
assert(self.networkStream == nil); // don't tap send twice in a row!
assert(self.fileStream == nil); // ditto
// First get and check the URL.
...
....
.....
// If the URL is bogus, let the user know. Otherwise kick off the connection.
...
....
.....
if ( ! success) {
self.statusLabel.text = @"Invalid URL";
} else {
// Open a stream for the file we're going to send. We do not open this stream;
// NSURLConnection will do it for us.
self.fileStream = [NSInputStream inputStreamWithFileAtPath:filePath];
assert(self.fileStream != nil);
[self.fileStream open];
// Open a CFFTPStream for the URL.
self.networkStream = CFBridgingRelease(
CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef) url)
);
assert(self.networkStream != nil);
if ([self.usernameText.text length] != 0) {
success = [self.networkStream setProperty:self.usernameText.text forKey:(id)kCFStreamPropertyFTPUserName];
assert(success);
success = [self.networkStream setProperty:self.passwordText.text forKey:(id)kCFStreamPropertyFTPPassword];
assert(success);
}
self.networkStream.delegate = self;
[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
///////******** LINE ADDED BY ME TO DISONNECT FROM FTP AFTER CLOSING CONNECTION *********////////////
[self.networkStream setProperty:(id)kCFBooleanFalse forKey:(id)kCFStreamPropertyFTPAttemptPersistentConnection];
///////******** END LINE ADDED BY ME *********////////////
[self.networkStream open];
// Tell the UI we're sending.
[self sendDidStart];
}
}
- (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];
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
#pragma unused(aStream)
assert(aStream == self.networkStream);
switch (eventCode) {
case NSStreamEventOpenCompleted: {
[self updateStatus:@"Opened connection"];
} break;
case NSStreamEventHasBytesAvailable: {
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventHasSpaceAvailable: {
[self updateStatus:@"Sending"];
// If we don't have any data buffered, go read the next chunk of data.
if (self.bufferOffset == self.bufferLimit) {
NSInteger bytesRead;
bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];
if (bytesRead == -1) {
[self stopSendWithStatus:@"File read error"];
} else if (bytesRead == 0) {
[self stopSendWithStatus:nil];
} else {
self.bufferOffset = 0;
self.bufferLimit = bytesRead;
}
}
// If we're not out of data completely, send the next chunk.
if (self.bufferOffset != self.bufferLimit) {
NSInteger bytesWritten;
bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self stopSendWithStatus:@"Network write error"];
} else {
self.bufferOffset += bytesWritten;
}
}
} break;
case NSStreamEventErrorOccurred: {
[self stopSendWithStatus:@"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
// FOR WHATEVER REASON THIS IS NEVER CALLED!!!!
} break;
default: {
assert(NO);
} break;
}
}
你的问题可以有两种解释。如果您要问的是“我有一个NSOutputStream,我已经写完了,我如何向它发送信号?”那么答案很简单,只需在它上面调用
close
方法即可
或者,如果您真正想说的是“我有一个NSInputStream,我想知道我何时到达流的末尾”,那么您可以查看hasBytesAvailable
或streamStatus==NSStreamStatusAtEnd
供您参考,要实际获取状态NSStreamStatusWriting
,您需要在该线程调用write:maxLength:
时从另一个线程调用streamStatus方法
---编辑:代码建议
您永远不会收到通知的原因是输出流是永远不会完成的(除非它是固定大小的流,而FTP流不是)。输入流“完成”,此时您可以关闭输出流。这就是你原来问题的答案
作为进一步的建议,除了处理输出流上的错误之外,我将跳过运行循环调度和“事件处理”。然后,我将读/写代码放入NSOperation子类中,并将其发送到NSOperationQueue中。通过保留对该队列中NSO操作的引用,您可以轻松地取消这些操作,甚至可以通过添加percentComplete属性来显示进度条。我已经测试了下面的代码,它可以工作。用FTP输出流替换我的内存输出流。您会注意到我跳过了验证,当然您应该保留这些验证。它们可能应该在NSO操作之外完成,以便于查询用户
@interface NSSendFileOperation : NSOperation<NSStreamDelegate> {
NSInputStream *_inputStream;
NSOutputStream *_outputStream;
uint8_t *_buffer;
}
@property (copy) NSString* sourceFilePath;
@property (copy) NSString* targetFilePath;
@property (copy) NSString* username;
@property (copy) NSString* password;
@end
@implementation NSSendFileOperation
- (void) main
{
static int kBufferSize = 4096;
_inputStream = [NSInputStream inputStreamWithFileAtPath:self.sourceFilePath];
_outputStream = [NSOutputStream outputStreamToMemory];
_outputStream.delegate = self;
[_inputStream open];
[_outputStream open];
_buffer = calloc(1, kBufferSize);
while (_inputStream.hasBytesAvailable) {
NSInteger bytesRead = [_inputStream read:_buffer maxLength:kBufferSize];
if (bytesRead > 0) {
[_outputStream write:_buffer maxLength:bytesRead];
NSLog(@"Wrote %ld bytes to output stream",bytesRead);
}
}
NSData *outputData = [_outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
NSLog(@"Wrote a total of %lu bytes to output stream.", outputData.length);
free(_buffer);
_buffer = NULL;
[_outputStream close];
[_inputStream close];
}
- (void) stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
// Handle output stream errors such as disconnections here
}
@end
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSOperationQueue *sendQueue = [[NSOperationQueue alloc] init];
NSSendFileOperation *sendOp = [[NSSendFileOperation alloc] init];
sendOp.username = @"test";
sendOp.password = @"test";
sendOp.sourceFilePath = @"/Users/eric/bin/data/english-words.txt";
sendOp.targetFilePath = @"/Users/eric/Desktop/english-words.txt";
[sendQueue addOperation:sendOp];
[sendQueue waitUntilAllOperationsAreFinished];
}
return 0;
}
@接口NSSendFileOperation:NSOperation{
NSInputStream*_inputStream;
NSOutputStream*_outputStream;
uint8\u t*\u缓冲区;
}
@属性(复制)NSString*sourceFilePath;
@属性(复制)NSString*targetFilePath;
@属性(副本)NSString*用户名;
@属性(副本)NSString*密码;
@结束
@NSSendFileOperation的实现
-(无效)主要
{
静态int kBufferSize=4096;
_inputStream=[NSInputStream inputStreamWithFileAtPath:self.sourceFilePath];
_outputStream=[NSOutputStream outputStreamToMemory];
_outputStream.delegate=self;
[_inputstreamopen];
[_outputstreamopen];
_buffer=calloc(1,kBufferSize);
while(_inputStream.hasbytes可用){
NSInteger bytesRead=[\u inputStream read:\u buffer maxLength:kBufferSize];
如果(字节读取>0){
[_outputstreamwrite:_buffermaxlength:bytesRead];
NSLog(@“将%ld个字节写入输出流”,字节读取);
}
}
NSData*outputData=[\u outputStream PropertyWorkey:NSStreamDataWriteEntomerStreamKey];
NSLog(@“向输出流写入了总共%lu个字节。”,outputData.length);
自由(_缓冲区);
_缓冲区=空;
[_outputstreamclose];
[_输入流关闭];
}
-(void)流:(NSStream*)aStream handleEvent:(NSStreamEvent)事件代码
{
//在此处处理输出流错误,例如断开连接
}
@结束
int main(int argc,const char*argv[]
{
@自动释放池{
NSOperationQueue*sendQueue=[[NSOperationQueue alloc]init];
NSSendFileOperation*sendOp=[[NSSendFileOperation alloc]init];
sendOp.username=@“测试”;
sendOp.password=@“测试”;
sendOp.sourceFilePath=@“/Users/eric/bin/data/english words.txt”;
sendOp.targetFilePath=@“/Users/eric/Desktop/english words.txt”;
[sendQueue addOperation:sendOp];
[sendQueue WaitUntillalOperations完成];
}
返回0;
}
你好!我的情况是:inputstream读取文件,outputstream将其写入ftp服务器。当inputstream完成写入缓冲区时,我关闭连接。但是这造成了一个问题,因为当我关闭连接时,输出流没有将整个缓冲区写入ftp。因此,我需要知道outputstream何时完成写入,以便在不切断文件结尾的情况下关闭连接。谢谢然后,问题不在于关闭输入流,而在于释放缓冲区(输入流和缓冲区是两个不同的对象),在缓冲区中读取数据。如果您已经完成了输入的读取,那么您已经将所有数据复制到了缓冲区中,因此可以关闭输入流。只有在完成对输出流的写入后才释放缓冲区。关闭输出流会产生问题。我不得不禁用“attemptPersistentConnection”,因为我不能让连接一直打开。因此,上传文件后,我必须关闭outputstream。问题是我不知道outputstream什么时候完成它的工作。我只知道输入流何时完成。这是完全相同的问题,没有答案:可能从不同的线程调用NSStreamStatus
会告诉我何时可以安全地关闭连接。。但是我怎么能做到呢?我是说,我怎么能从不同的线程调用它?