我有一个小功能可以与我的 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% 确定消息是从我的服务器正确发送的。仅当消息很大且数据很多时才会出现此问题。