iOS流在中间切断长消息

iOS流在中间切断长消息,ios,iphone,objective-c,Ios,Iphone,Objective C,我有一个与我的Nodejs服务器对话的小功能: - (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { NSLog(@"stream event %i", streamEvent); switch (streamEvent) { case NSStreamEventOpenCompleted: NSLog(@"Stream opened"

我有一个与我的Nodejs服务器对话的小功能:

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    NSLog(@"stream event %i", streamEvent);

    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) {

                            // Parse the message and add it to the right method
                            NSError* error;
                            NSDictionary *JSON =
                            [NSJSONSerialization JSONObjectWithData: [output dataUsingEncoding:NSUTF8StringEncoding]
                                                            options: NSJSONReadingMutableContainers
                                                              error: &error];

                            NSString* type = [JSON objectForKey:@"type"];

                            NSLog(@"SERVER TYPE: %@\n", type);
                            NSLog(@"SERVER SENT: %@\n", output);

                            if([type isEqualToString:@"visitorLoad"]) {
                                NSLog(@"New visitor load: %@", output);
                                [self visitorReceived:output];

                            } else if([type isEqualToString:@"message"]) {
                                NSLog(@"New chat message: %@", output);

                                [self messageReceived:output];

                            } else if([type isEqualToString:@"offlineMessages"]) {
                                //NSLog(@"New offline messages: %@", output);
                                NSLog(@"NEW OFFLINE MESSAGES!!");
                                [self offlineMessagesReceived:output];

                            } else if([type isEqualToString:@"agentMsg"]) {
                                NSLog(@"New AGENT MESSAGE: %@", output);

                                [self agentMessageReceived:output];

                            } else if([type isEqualToString:@"heartbeat"]) {
                                // Take no action
                                NSLog(@"Heartbeat recieved");

                            } else if([type isEqualToString:@"visitorExit"]) {

                                [self visitorHasGoneOffline:output];

                            }
                        }
                    }
                }
            }
            break;


        case NSStreamEventErrorOccurred:

            NSLog(@"Can not connect to the host!");
            isConnected = 0;
            //[self initNetworkCommunication];
            break;

        case NSStreamEventEndEncountered:

            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            //[theStream release];
            NSLog(@"STREAM PAUSED");
            theStream = nil;

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

}
问题是,当我从我的节点服务器发送大型JSON消息时,上面的代码会将其分成多个部分,使我无法解析

这是我打开流的方式:

// Open connection to server
- (void)initNetworkCommunication {
    isConnected = TRUE;
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"server.com", 8080, &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];

    [self openDB];
    [self createTable];
}

你知道这是什么原因吗?我100%确定邮件从我的服务器正确发送。只有当消息较大且包含大量数据时,才会出现此问题。

我在NSURLConnection中遇到了完全相同的问题。大数据似乎被切成两半,导致JSON转换产生空值

也许你应该把所有的数据合并在一起

case NSStreamEventHasBytesAvailable
   NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
   wholeString  = [wholeString stringByAppendString:output];
然后在中转换为JSON

    case NSStreamEventEndEncountered
       NSDictionary *JSON =[NSJSONSerialization JSONObjectWithData: [wholeString dataUsingEncoding:NSUTF8StringEncoding]
                                                                options: NSJSONReadingMutableContainers
                                                                  error: &error];
       ...

祝你好运

好了。试一试

    case NSStreamEventHasBytesAvailable:

uint8_t buffer[1024];
int len;
NSMutableData *data = [[NSMutableData alloc] init];
while ([inputStream hasBytesAvailable]) {
   len = [inputStream read:buffer maxLength:sizeof(buffer)];
   if (len > 0) {
       [data appendBytes:buffer length:len];
   }
}


NSError* error;
NSDictionary *JSON =[NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];

不幸的是:(哦,这正是我的问题,流被切碎,JSON转换产生NULL。它被调用了一次,但是数据被切碎了。
而([inputStream hasBytesAvailable])
被调用的次数与数据被切碎的次数一样多,无论我如何增加
uint8\u t buffer[5000000]
它似乎可以工作!获取错误
***由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[nsConcreteMatableData数据使用编码:]:无法识别的选择器发送到实例0xa045a70'
我编辑了上面的帖子并删除了缓冲区前的&符号。请重试。获取此信息:
***由于未捕获异常“NSInvalidArgumentException”终止应用程序,原因:'-[nsContectEmutableData dataUsingEncoding::无法识别的选择器发送到实例0xa00fc50'