2012-01-02 32 views
3

我嘗試使用NSStream從/向Socket讀寫數據。這裏是我的代碼用於連接:當字節可用時,NSInputStream讀取返回無符號整數最大值

- (void)connect 
{ 
    [NSStream getStreamsToHostNamed:APIC_HOST_ADDR 
          port:APIC_HOST_PORT 
         inputStream:&inStream 
        outputStream:&outStream]; 
    [inStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; 
    [outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; 

    inStream.delegate = self; 
    outStream.delegate = self; 

    if ([inStream streamStatus] == NSStreamStatusNotOpen) 
    [inStream open]; 

    if ([outStream streamStatus] == NSStreamStatusNotOpen) 
    [outStream open]; 

} 

和輸入流我實現委託方法來收到事件

- (void)handleInputStreamEvent:(NSStreamEvent)eventCode 
{ 
    switch (eventCode) { 
    case NSStreamEventHasBytesAvailable: 
    { 
    int bytesRead; 
    if (data == nil) { 
     data = [[NSMutableData alloc] init]; 
    } 
    uint8_t buf[1024]; 
    unsigned int len = 0; 
    len = [inStream read:buf maxLength:1024]; 
    if(len>0) { 
     @try { 
     [data appendBytes:(const void *)buf length:len]; 
     } 
     @catch (NSException *exception) { 
     NSLog(@"Fail: %@", exception); 
     } 
     @finally { 
     NSLog(@"Finally"); 
     bytesRead += len; 
     } 
    } else { 
     NSLog(@"No Buffer"); 
    } 

    NSString *str = [[NSString alloc] initWithData:data 
              encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",str); 
    [str release]; 
    [data release];   
    data = nil; 
    } break; 
    case NSStreamEventErrorOccurred: 
    { 
     NSError *theError = [inStream streamError]; 
     NSLog(@"Error reading stream! ,Error %i: %@",[theError code], [theError localizedDescription]); 
     [self disconnect]; 
     [self connect]; 
    } break; 
    } 
} 

[NSStream read:maxLength:]總是返回最大的無符號整型值。最終我得到這個錯誤:

Fail: *** -[NSConcreteMutableData appendBytes:length:]: unable to allocate memory for length (4294967295) 

爲什麼閱讀mehod返回這個大的價值?它真的讀了那麼多字節嗎? (我不這麼認爲):)

PS:套接字流服務器是好的。它也讀取和寫入數據到其他客戶端也沒有問題。

回答

3

我解決了這個問題。我在寫數據時沒有注意輸出流是否有可用空間。

3

從NSInputStream讀取:最大長度文檔:

Return Value A number indicating the outcome of the operation A positive number indicates the number of bytes read 0 indicates that the end of the buffer was reached A negative number means that the operation failed

所以在流您LEN結束的情況下爲0,在錯誤的情況下,它是-1,說明你的unsigned int類型的值4294967295。

所以使用signed int並檢查負值。

0

如果從CFReadStreamRead()方法返回1,表示請求失敗,則應該進行失敗處理。 CFReadStreamRead()方法讀取失敗將返回1,與4294967295-1是相同的內存塊,所以長度爲4294967295.

+0

@Arthur Korchagin好的,謝謝。 – leopardpan 2015-11-20 10:39:19

相關問題