我正在使用此实现连接到服务器套接字,当我尝试连接到不存在的套接字服务器时,它进入无限循环,如何设置超时?
+ (void)getStreamsToHostNamed:(NSString *)hostName
port:(NSInteger)port
inputStream:(NSInputStream **)inputStreamPtr
outputStream:(NSOutputStream **)outputStreamPtr
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
assert(hostName != nil);
assert((port > 0) && (port < 65536));
assert((inputStreamPtr != NULL) || (outputStreamPtr != NULL));
readStream = NULL;
writeStream = NULL;
CFStreamCreatePairWithSocketToHost(
NULL,
(CFStringRef) hostName,
port,
((inputStreamPtr != nil) ? &readStream : NULL),
((outputStreamPtr != nil) ? &writeStream : NULL)
);
if (inputStreamPtr != NULL) {
*inputStreamPtr = [NSMakeCollectable(readStream) autorelease];
}
if (outputStreamPtr != NULL) {
*outputStreamPtr = [NSMakeCollectable(writeStream) autorelease];
}
}
@end
@implementation sockets
@synthesize iStream;
@synthesize oStream;
@synthesize model;
- (void) connect: (NSString*) IPAdress and:(NSInteger) porto{
NSString *temporary = [NSString stringWithFormat: @"%@", IPAdress];
[NSStream getStreamsToHostNamed:temporary port:porto
inputStream:&iStream
outputStream:&oStream];
[iStream retain];
[oStream retain];
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
[oStream open];
NSLog (@"Conectado");
}
提前致谢!
最佳答案
如果您想要超时,请安排一个计时器。如果计时器在 NSStreamEventOpenCompleted
到达之前触发,那么您已经超时。做出适当的响应(关闭流等)。
关于iphone - 套接字超时 - 需要帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5460803/