我创建了一个实现MySocketClient的NSStreamDelegate类,并实现了方法- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
然后调用bellow函数连接服务器:
- (void)connectToHost:(NSString *)host onPort:(UInt32)port{
NSLog(@"will connect...");
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
_inputStream = (__bridge NSInputStream *)readStream;
_outputStream = (__bridge NSOutputStream *)writeStream;
_inputStream.delegate = self;
_inputStream.delegate = self;
[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
}连接我的服务器是很棒的,但是委托方法:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
未被调用.
在AppDelegate.m文件的方法- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中调用‘- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions’,如下所示:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{ GoEasySocketClient *GoEasySocketClient= [GoEasySocketClient alloc init];client connectToHost:@"myhost“onPort:myport;};
但奇怪的是,如果我使用AppDelegate作为NSStreamDelegate,并实现方法- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
当我调用connectToHost方法时,将调用委托方法- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode,而eventCode是NSStreamEventOpenCompleted。
发布于 2016-03-03 13:01:52
在使用第二个线程时,应该根据苹果文档运行自己的run循环。因此,就您的情况而言,应该如下所示:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
GoEasySocketClient *client = [[GoEasySocketClient alloc] init];
[client connectToHost:@"myhost" onPort:myport];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
});或者您可以使用[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]]而不是[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]。唯一的区别是,第一个“在处理第一个输入源或到达limitDate之后”返回,而另一个“通过反复调用runMode:limitDate:直到指定的过期日期在NSDefaultRunLoopMode中运行接收器”。
我用NSURLConnection尝试了第一个,它工作得很好。
还可以使用主线程的run循环。在这种情况下,您应该按以下方式更改代码:
[_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];关于你的问题:
但奇怪的是,如果我使用AppDelegate作为NSStreamDelegate,并实现方法-(Void)流:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode,当我调用connectToHost方法时,委托方法-(Void)流:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode将被调用,eventCode是NSStreamEventOpenCompleted。
之所以发生这种情况,是因为您使用自己的run循环从主线程调用connectToHost方法。此运行循环在应用程序启动期间自动启动。
https://stackoverflow.com/questions/35745273
复制相似问题