gpt4 book ai didi

iPhone:使用 NSStream 捕获连接错误

转载 作者:行者123 更新时间:2023-12-03 16:07:31 27 4
gpt4 key购买 nike

我编写了一个程序,使用 Apple 流编程指南中概述的 NSStream 协议(protocol)连接到给定 IP 上的服务器。数据的连接和传输工作完美,但是如果用户指定了错误的 IP 并且程序尝试打开流,则会导致程序无响应。

据我所知,handleEvent 方法检测到流错误,但是当我检查 eventCode == NSStreamEventErrorOccurred 的条件时,似乎没有发生任何事情。我的连接代码如下:

NSString *hostString = ipField.text;

CFReadStreamRef readStream;

CFWriteStreamRef writeStream;

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)hostString, 10001, &readStream, &writeStream);



inputStream = (NSInputStream *)readStream;

outputStream = (NSOutputStream *)writeStream;

[inputStream setDelegate:self];

[outputStream setDelegate:self];

[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[inputStream open];

[outputStream open];

知道如何在无法建立连接时指定超时值或允许按钮触发流的关闭吗?

最佳答案

Any idea as to how I can specify a timeout value or allow for a button to trigger the closing of the streams if a connection cannot be made?

使用NSTimer

在你的.h中:

...
@interface MyViewController : UIViewController
{
...
NSTimer* connectionTimeoutTimer;
...
}
...

在你的.m中:

...
@interface MyViewController ()
@property (nonatomic, retain) NSTimer* connectionTimeoutTimer;
@end

@implementation MyViewController

...
@synthesize connectionTimeoutTimer;
...

- (void)dealloc
{
[self stopConnectionTimeoutTimer];
...
}

// Call this when you initiate the connection
- (void)startConnectionTimeoutTimer
{
[self stopConnectionTimeoutTimer]; // Or make sure any existing timer is stopped before this method is called

NSTimeInterval interval = 3.0; // Measured in seconds, is a double

self.connectionTimeoutTimer = [NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(handleConnectionTimeout:)
userInfo:nil
repeats:NO];
}

- (void)handleConnectionTimeout
{
// ... disconnect ...
}

// Call this when you successfully connect
- (void)stopConnectionTimeoutTimer
{
if (connectionTimeoutTimer)
{
[connectionTimeoutTimer invalidate];
[connectionTimeoutTimer release];
connectionTimeoutTimer = nil;
}
}

关于iPhone:使用 NSStream 捕获连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3687177/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com