-1

我正在尝试将 json 对象发送到服务器。但我收到一个错误,我无法修复它。

-(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:函数。

现在,在我将 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);

我只是复制并粘贴这部分代码。可能是什么问题!

4

1 回答 1

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
于 2012-08-10T12:59:39.843 回答