我正在编写一个消息应用程序,它使用 NSStream 与用 Python 编写的服务器进行通信。服务器与配套的 Python 客户端完美配合。但是当我用 NSStream 连接到它时, NSInputStream 似乎没有得到任何数据。然而,NSOutputStream 可以完美运行。我像这样打开字符串:
-(void)openStream
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"tihmstar.dyndns.org", 80, &readStream, &writeStream);
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
[self auth];
[[NSNotificationCenter defaultCenter] postNotificationName:@"InitCompleted" object:nil];
}
委托方法是这样的:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
NSLog(@"Handle Event - ");
switch (streamEvent)
{
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"Bytes Available!");
if(theStream == inputStream)
{
NSLog(@"inputStream is ready.");
uint8_t buf[1024];
unsigned int len = 0;
len = [inputStream read:buf maxLength:1024];
if(len > 0)
{
NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
[data appendBytes: (const void *)buf length:len];
NSString* string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Server said- %@", string);
[self messageReceived:[string lowercaseString]];
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
NSLog(@"End Encountered");
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"Space Availible.");
break;
default:
NSLog(@"Unknown event- %u", streamEvent);
}
}
我的问题是这种情况 NSStreamEventHasBytesAvailable 永远不会被调用,因此永远不会收到来自服务器的消息。有人对此有任何解决方案吗?我在 StackOverflow 上找到了一些相关的问题,但没有一个得到回答。
提前致谢。