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% 確信しています。この問題は、メッセージが大量のデータを含む大規模な場合にのみ発生します。