gpt4 book ai didi

ios - NSStream 委托(delegate) NSStreamEventHasBytesAvailable 未被调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:20:35 25 4
gpt4 key购买 nike

我正在编写一个使用 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];
}

委托(delegate)方法如下:

- (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 上发现了一些相关问题,但没有一个得到解答。

提前致谢。

最佳答案

我只是在研究代码。尝试删除 NSInputStream 的委托(delegate)。我正在调查另一个 Using NSXMLParser initWithStream: no parser delegate methods received

它处理类似的情况。

关于ios - NSStream 委托(delegate) NSStreamEventHasBytesAvailable 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18796556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com