2012-08-10 49 views
-1

我想發送json對象到服務器。但我收到一個錯誤,我無法修復它。NSJSONSerialization錯誤

-(void) connectToHost{ 
CFReadStreamRef readStream; 
CFWriteStreamRef writeStream; 
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 9123, &readStream, &writeStream); 
inputStream = (__bridge NSInputStream *)readStream; 
outputStream = (__bridge NSOutputStream *)writeStream; 
[inputStream setDelegate:self]; 
[outputStream setDelegate:self]; 
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[inputStream open]; 
[outputStream open]; } 

這是我與主機的連接。

NSDictionary *setUser = [NSDictionary 
      dictionaryWithObjectsAndKeys:[@"u" stringByAppendingString:my.id],@"id", 
             @"GET_USER_INFO",@"command", 
             @"",@"value", 
             nil]; 
    NSArray *array = [NSArray arrayWithObject:setUser]; 
    jsonDataToSendTheServer = [array JSONRepresentation]; 
    NSLog(@" %@ ", jsonDataToSendTheServer); 
    // array = [NSArray arrayWithObject:jsonDataToSendTheServer]; 
    NSLog(@" %@ ", array); 
    NSLog(@"true or false %c",[NSJSONSerialization 
           isValidJSONObject: array]); 

    bytesWritten = [NSJSONSerialization writeJSONObject:array toStream:outputStream options:NSJSONWritingPrettyPrinted error:nil]; 

而這部分是NSJSONSerialization部分。 但是我得到一個錯誤。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***+[NSJSONSerialization writeJSONObject:toStream:options:error:]: stream is not open for writing' 

我是新來的objective-c。我無法解決問題3個小時。

=======================================

編輯:

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { 

NSLog(@"stream event %i", streamEvent); //this doesn't post in the log when stream opened... 
NSLog(@"bytes %i",bytesWritten); 
switch (streamEvent) { 

    case NSStreamEventOpenCompleted: 
     NSLog(@"Stream opened"); 
     break; 
    case NSStreamEventHasBytesAvailable: 

     if (theStream == inputStream) { 

      uint8_t buffer[1024]; 
      int len; 

      while ([inputStream hasBytesAvailable]) { 
       len = [inputStream read:buffer maxLength:sizeof(buffer)]; 
       if (len > 0) { 

        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; 

        if (nil != output) { 

         NSLog(@"server said: %@", output); 
         //[self messageReceived:output]; 

        } 
       } 
      } 
     } 
     break; 

    case NSStreamEventEndEncountered: 

     [theStream close]; 
     [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
     //[theStream release]; 
     theStream = nil; 

     break; 
    case NSStreamEventHasSpaceAvailable: 
    { 
     uint8_t *readBytes = (uint8_t *)[_data mutableBytes]; 
     readBytes += bytesWritten; // instance variable to move pointer 
     int data_len = [_data length]; 
     unsigned int len = ((data_len - bytesWritten >= 1024) ? 
          1024 : (data_len-bytesWritten)); 
     uint8_t buf[len]; 
     (void)memcpy(buf, readBytes, len); 
     //len = [theStream write:(const uint8_t *)buf maxLength:len]; 
     NSLog(@"written %s", buf); 
     bytesWritten += len; 
    } 
     break; 

    case NSStreamEventErrorOccurred: 
    { 
     NSLog(@"no connection"); 
    } 
    case NSStreamEventNone: 
    { 
     //printf("EVENT: None.\n"); 
     break; 
    } 

    default: 
     NSLog(@"Unknown event"); 
}} 

這是我的流:handleEvent:function。

現在我沒有添加connectionToHost委託我得到這種錯誤。

012-08-10 16:14:27.302 TaraftarlikOyunu[2274:c07] written P∏◊P‡ˇø 

2012-08-10 16:14:28.399 TaraftarlikOyunu[2274:c07] benim bu id 587127341 

2012-08-10 16:14:28.399 TaraftarlikOyunu[2274:c07] benim ad Ahmet 

2012-08-10 16:14:28.400 TaraftarlikOyunu[2274:c07] 

[{"id":"u581277341","command":"GET_USER_INFO","value":""}] 


2012-08-10 16:14:28.404 TaraftarlikOyunu[2274:c07] stream event 4 

2012-08-10 16:14:28.404 TaraftarlikOyunu[2274:c07] bytes 86 

    (lldb) 

現在我沒有一個想法,如果緩存或不

======================= EDIT2 = ============== 抱歉。 問題可能出現,因爲這

(void)memcpy(buf, readBytes, len); 

我只是複製並粘貼這部分代碼。 可能是什麼問題!

+0

你肯定已經發生了,你需要JSON發送到原始套接字?很不尋常的組合。 – Farcaller 2012-08-10 12:52:46

+0

是的,你應該做一個簡單的HTTP請求 – 2012-08-10 13:00:14

+0

如果你的新目標C請參閱NSURLConnection和NSURLRequest。你所做的是爲網絡流編程量身定做的,這比你需要的要多。 – 2012-08-10 13:01:50

回答

1

您使用的連接方法有點多。

您需要確保連接在委託

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { 

switch (streamEvent) { 
    case NSStreamEventHasSpaceAvailable: 
     NSLog(@\"None!\"); 
     break; 
    case NSStreamEventOpenCompleted: 
     NSLog(@\"Stream opened\"); 
       //NOW you can write to the stream 
相關問題