質問

I'm trying to send json object to server. But I received an error and I can't fix it.

-(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];    }

This is my connection to host.

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];

and this part is NSJSONSerialization part. However I got an error.

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

I'm new at objective-c. I can't fix the problem for 3 hours.

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

edit:

- (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");
}}

this is my stream: handleEvent: function.

Now after I did add the connectionToHost to delegate I get this kind of error.

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) 

now I don't have an idea that if it buffered or not

=======================EDIT2=============== sorry about this. the problem probably appears because of this

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

I just copy and paste this part of code. what may be the problem!

役に立ちましたか?

解決

The connection method you are using is a little much.

You need to make sure the connection has happened in the delegate

    - (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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top