我在网上搜索了很长时间......我没有找到我的问题的答案,所以我决定在这里发布。我尝试使用 NSStream 建立与 NNTP 服务器的连接。
在测试程序中,我打开流并发送消息。委托方法 ( stream:handleEvent:
) 为输出流 ( NSStreamEventOpenCompleted
, NSStreamEventHasSpaceAvailable
) 调用了两次,但从不为输入流调用!
为什么输入流从不调用委托?有任何想法吗?
基本上,代码如下所示:
初始化和打开流:
CFReadStreamRef tmpiStream;
CFWriteStreamRef tmpoStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)SERVER, PORT, &tmpiStream, &tmpoStream);
iStream = (__bridge NSInputStream *) tmpiStream;
oStream = (__bridge NSOutputStream *)tmpoStream;
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
[oStream open];
发信息:
NSData *data = [[NSData alloc] initWithData:[messageString dataUsingEncoding:NSASCIIStringEncoding]];
[oStream write:[data bytes] maxLength:[data length]];
接收消息:
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
NSLog(@"EventCode: %i", eventCode);
//switch-case-statement...(using constants - NSStreamEventOpenCompleted...)
}
包含该代码的类继承自 NSObjects 并实现NSStreamDelegate
。(带有 ARC 的 iOS5)
感谢您的帮助!
编辑:我只是在打开这样的流后尝试“轮询” - 它正在工作:
while (![iStream hasBytesAvailable])
{}
uint8_t buffer[1024];
int len;
NSString *str = @"";
while ([iStream hasBytesAvailable])
{
len = [iStream read:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSISOLatin1StringEncoding];
if (output != nil)
{
str = [str stringByAppendingString:output];
}
}
}
NSLog(@"Response: %@", str);
但是,可以肯定的是,我仍然需要一个更好的(异步)解决方案;)