I create a MySocketClient class which implements NSStreamDelegate, and implements the method - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
and then call the bellow function to connect the server:
- (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];
}
It is great to connect my server, but the delegate method:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
not called.
The 'connectToHost' is called in the method - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
of AppDelegate.m file as bellow shown:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ GoEasySocketClient *client = [[GoEasySocketClient alloc] init]; [client connectToHost:@"myhost" onPort:myport]; });
But the strange thing is if I use the AppDelegate as the NSStreamDelegate, and implement the method - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
and when I call connectToHost
method, the delegate method - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
will be called and the eventCode is NSStreamEventOpenCompleted
.