套接字超时 - 需要帮助

时间:2011-03-28 14:52:41

标签: iphone objective-c cocoa-touch sockets

我正在使用此实现连接到服务器套接字,当我尝试连接到一个不可用的套接字服务器时,它进入无限循环,我该如何设置超时?

+ (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");


}

提前致谢!

1 个答案:

答案 0 :(得分:4)

如果您想要超时,请安排计时器。如果计时器在NSStreamEventOpenCompleted到来之前触发,那么你已经超时了。适当回应(关闭流等)。