NSStreamDelegate读取异步数据

时间:2013-01-20 17:36:32

标签: iphone ios asynchronous stream

行。因此,我必须处理NSStreamDelegate实现的特殊情况。

该过程如下:

1- a COMMAND数据被写入输出流以触发另一端

2-另一端,开始异步输入输入流BUT的数据,这意味着数据的第一部分在开始时被接收,然后几秒钟,其余的数据进入。

3-收到所有数据后,服务器将不发送任何数据,但连接仍保持打开状态。 (输入流状态=打开(2))

4-几分钟后,服务器结束连接(输入流状态= 5)并触发NSStreamEventEndEncountered。

SendRequest类

- (void)sendSecondRequest {
    CFReadStreamRef readStream = nil;
    CFWriteStreamRef writeStream = nil;
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)self.SOMEServer, self.SOMEPort, &readStream, &writeStream);
    self.inputStream = (__bridge NSInputStream *)readStream;
    self.outputStream = (__bridge NSOutputStream *)writeStream;
    [self.inputStream setDelegate:self];
    [self.outputStream setDelegate:self];
    NSData *data = [NSData dataWithData:[kSecondCall dataUsingEncoding:NSASCIIStringEncoding]];
    [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream open];
    [self.outputStream open];
    [self.outputStream write:[data bytes] maxLength:[data length]];
}

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
    switch (eventCode) {
        case NSStreamEventOpenCompleted:
            break;
        case NSStreamEventHasBytesAvailable:
            if (aStream == self.inputStream) {
                uint8_t buffer[1024];
                NSInteger len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
                if (len > 0) {
                    NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
                    [gOutput appendString:output];
                }
            }
            break;
        case NSStreamEventEndEncountered:
            NSLog(@"Can not connect to the host");
            [aStream close];
            [aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            aStream = nil;
            break;
        default:
            break;
    }
}

- (void)disconnectSocket {
    [self.inputStream close];
    [self.inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream close];
    [self.outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream setDelegate:nil];
    [self.outputStream setDelegate:nil];
    self.inputStream = nil;
    self.outputStream = nil;
}

gOutput 变量是一个全局变量,用于读取和存储输入流。

问题在于,由于数据的第一部分立即出现,然后其余部分以异步方式进入,我无法处理没有更多可用数据的时刻。

换句话说,我怎么知道服务器是否完成了发送数据,我应该开始处理它?<​​/ p>

1 个答案:

答案 0 :(得分:0)

服务器在末尾发送终结符序列。当客户端检测到此终结符时,它开始处理....