美文网首页
NSStream,NSInputStream,NSOutputS

NSStream,NSInputStream,NSOutputS

作者: heart_领 | 来源:发表于2018-11-22 15:03 被阅读13次
//NSInputStream
[self setUpStreamForFile:@"jiahongling"];
- (void)setUpStreamForFile:(NSString *)path{
    NSInputStream *inputStream = [[NSInputStream alloc] initWithData:[path dataUsingEncoding:NSUTF8StringEncoding]];
    inputStream.delegate = self;
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    NSLog(@"%lu**%@**%d",(unsigned long)inputStream.streamStatus,inputStream.streamError,inputStream.hasBytesAvailable);
}

//NSOutputStream
self.data1 = [[NSMutableData alloc]initWithData:[@"jiahongling" dataUsingEncoding:NSUTF8StringEncoding]];
-(void)createOutputStream{
    self.outStream = [[NSOutputStream alloc]initToMemory];
    self.outStream.delegate = self;
    [self.outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outStream open];
}

//代理

/**
 2018-12-17 17:41:40.477599+0800 afn_demo[96000:6143519] 🔥:ji***2
2018-12-17 17:41:40.479018+0800 afn_demo[96000:6143519] 🔥:jiah***2
2018-12-17 17:41:40.479876+0800 afn_demo[96000:6143519] 🔥:jiahon***2
2018-12-17 17:41:40.480088+0800 afn_demo[96000:6143519] 🔥:jiahongl***2
2018-12-17 17:41:40.480351+0800 afn_demo[96000:6143519] 🔥:jiahonglin***2
2018-12-17 17:41:40.480909+0800 afn_demo[96000:6143519] 🔥:jiahongling***1
 */
//流中只要有内容,就会一直调用该方法
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    switch (eventCode) {
        case NSStreamEventNone: {
            NSLog(@"NSStreamEventNone");
            break;
        }
        case NSStreamEventOpenCompleted: {
            NSLog(@"NSStreamEventOpenCompleted");
            break;
        }
        case NSStreamEventHasBytesAvailable:
        {
            if (!self.data) {
                self.data = [NSMutableData data];
            }
            //把读取的内容放入提供的缓冲区中,该缓冲区大小至少是len长度。当内容长度大于最大长度时,返回最大长度,当内容长度小于最大长度时,返回内容的实际长度
            uint8_t buf[1024];//初始化的缓存最大值(无符号字符数组)
//        uint8_t:unsigned char
//        uint16_t:unsigned short
//        uint32_t:unsigned int
//        uint64_t:unsigned long long
            
            NSUInteger len = 0;
            len = [(NSInputStream *)aStream read:buf maxLength:2];  // 读取数据,读出的是j和i,maxLength为向缓冲区一次放入的最大长度,当NSInputStream中的数据长度大于maxLength时,每次放入的数据长度为maxLength,当NSInputStream中的数据长度小于maxLength时,放入的长度为NSInputStream中的数据长度。把buf看成银行,NSInputStream为10个人排的队列,maxLength为银行窗口,假入maxLength为3,则每次最多三个人可以从队列中出来办理业务,最后剩一个办理。
//            uint8_t buf1[1024];
//            NSUInteger len1 = 0;
//            len1 = [(NSInputStream *)aStream read:buf1 maxLength:2];//读出的是a和h
//            NSLog(@"🍎:%lu",strlen(buf));
//            把缓冲里的数据放入data,从首地址开始放入长度为len的数据
            if (len) {
                [self.data appendBytes:(const void *)buf length:len];
            }
            
            NSLog(@"🔥:%@***%lu",[[NSString alloc]initWithData:self.data encoding:NSUTF8StringEncoding],(unsigned long)len);
        }
            break;
            
            
        case NSStreamEventHasSpaceAvailable: {
            NSLog(@"NSStreamEventHasSpaceAvailable");
            uint8_t *readBytes = (uint8_t *)[self.data1 mutableBytes];//拿出data1中的字符串,data1中是二进制数据,此方法可以将data1中的二进制转化出来
            readBytes += byteIndex;//用于移动指针的实例变量,byteIndex初始值为0
           unsigned int data_len = (int)[self.data1 length];
             int len = (data_len - byteIndex >= 1024) ? 1024 : (data_len - byteIndex);
            
            uint8_t buf[len];
            /**
             第一个参数:缓存
             第二个参数:数据
             第三个参数:放入缓存中的数据长度,长度小于数据长度时,只能放一部分数据进入缓存
             */
           memcpy(buf, readBytes, len);//存入缓存,
            NSLog(@"存入缓存的数据:%s",buf);
            len = (int)[(NSOutputStream *)aStream write:(const uint8_t *)buf maxLength:len];//把缓存中的数据写入流中,len为0时停止,返回的是实际长度
            if (len>=0) {//执行三次,最后一次 len=-1
                byteIndex += len;
            }
            NSLog(@"哈哈哈哈:%d",byteIndex);
            
//            uint8_t * readBytes =(uint8_t *)[_data mutableBytes];
//            readBytes + = byteIndex; //用于移动指针的实例变量
//            int data_len = [_data length];
//            unsigned int len =((data_len  -  byteIndex >= 1024)?
//                               1024:(data_len-byteIndex));
//            uint8_t buf [len];
//            (void)memcpy(buf,readBytes,len);
//            len = [stream write:(const uint8_t *)buf maxLength:len];
//            byteIndex + = len;
//
            
            break;
        }
        case NSStreamEventErrorOccurred: {
            NSLog(@"NSStreamEventErrorOccurred");
            break;
        }
        case NSStreamEventEndEncountered: {//只有读或者写操作结束才会走这里,没有读或者写的操作,不会走到这里
            NSLog(@"NSStreamEventEndEncountered");
           NSData *data = [aStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
            if (data) {
                
                NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"🍎🍎🍎🍎🍎🍎:%@",str);
            }else{
                NSLog(@"无数据***无数据");
            }
            [aStream close];
            [aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            aStream = nil;
            break;
        }
    }
}


//循环
- (void)createNewFile {
    NSOutputStream *oStream = [[NSOutputStream alloc] initToMemory];
    [oStream open];
    uint8_t *readBytes = (uint8_t *)[self.data1 mutableBytes];//取出数据
    uint8_t buf[1024];//设置最大缓存
    int len = 1024;
    while (1) {
        if (len == 0) break;
        if ([oStream hasSpaceAvailable])
        {
            strncpy((char *)buf, (const char*)readBytes, len);
            readBytes += len;
            if ([oStream write:(const uint8_t *)buf maxLength:len] == -1)
            {
//                [self handleError:[oStream streamError]];
                NSLog(@"发生了错误❌❌❌❌❌");
                break;
            }
//            [bytesWritten setIntValue:[bytesWritten intValue]+len];
//            len = (([self.data length] - [bytesWritten intValue] >= 1024) ? 1024 : [data length] - [bytesWritten intValue]);
            len = 0;//为0就会跳出来
        }
    }
    NSData *newData = [oStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    if (!newData) {
        NSLog(@"No data written to memory!");
    } else {
//        [self processData:newData];
        NSString *s = [[NSString alloc]initWithData:newData encoding:NSUTF8StringEncoding];
        NSLog(@"ssssss:%@",s);
    }
    [oStream close];
    oStream = nil;
}

相关文章

网友评论

      本文标题:NSStream,NSInputStream,NSOutputS

      本文链接:https://www.haomeiwen.com/subject/rnylqqtx.html