Thank your answer.
I am trying to use CFStream to connect a server, as follows.
Now, I encountered two problems:
1. I do not know how to set timeout. When using CFSocket, I set timeout like this: CFSocketConnectToAddress(self.socket, sin_cfd, 3);
2. I do not know how to close the connection. I used the following method closeConnection to close the connection, although the connection is successfully closed but the subthread is not released.
Could you help me resovle the two problems ?
Thanks !
- (void)start
{
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(connectOnSubthread) object:nil];
[thread start];
}
- (void)connectOnSubthread
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)_domain, _port, &readStream, &writeStream);
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
_inputStream = (__bridge NSInputStream *)readStream;
_outputStream = (__bridge NSOutputStream *)writeStream;
_inputStream.delegate = self;
_outputStream.delegate = self;
[_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
[[NSRunLoop currentRunLoop] run];
}
- (void)closeConnection
{
[_inputStream close];
[_outputStream close];
_inputStream = nil;
_outputStream = nil;
}