2012-01-02 33 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) 

なぜこの大きな値を返すのですか?それは本当にそのたくさんのバイトを読んでいますか? (私はそうは思わない):)

PS:ソケットストリームサーバーはOKです。他のクライアントとの間でもデータの読み書きを行うため、問題はありません。

答えて

3

私はこの問題を解決しました。出力ストリームに空き容量があるかどうかを確認せずにデータを書き込んでいました。 NSInputStreamから

3

読み:maxLengthのドキュメント:

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値を説明しています。

符号付き整数を使用し、負の値をチェックします。

0

CFReadStreamRead()メソッドから1が返された場合、要求が失敗したことを意味します。失敗の処理を行う必要があります。 CFReadStreamRead()エラーを読み取るメソッドは1を返します.4294967295-1は同じメモリブロックなので、長さは4294967295です。

+0

@Arthur Korchagin OK、ありがとうございます。 – leopardpan

関連する問題