gpt4 book ai didi

objective-c - 如何检测网络断开?

转载 作者:行者123 更新时间:2023-12-03 17:15:26 26 4
gpt4 key购买 nike

我正在开发 Mac OS X 10.7/10.6 的网络应用程序。我需要检测网络问题。换句话说,我需要在没有互联网连接时进行检测。我尝试添加一些带有计时器的方法来连接到服务器,并在没有结果时显示消息。但我需要更多的实时解决方案。是否有一些关于网络断开的系统通知?

最佳答案

如果你使用 nsstreams,那么就这样做

标题:

@interface CrestronClient : UIViewController <NSStreamDelegate,UIAlertViewDelegate> {

NSInputStream *inputStream;
NSOutputStream *outputStream;

}
@end

.m 文件:

初始化值通常在连接方法中或确实加载

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, 192.168.1.1, 46651, &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];

unsigned char connectByteArray1[] = {
0x01, 0x00, 0x07, 0x7f, 0x00, 0x00, 0x01, 0x00, 0x03, 0x40
};

[outputStream write:connectByteArray1 maxLength:sizeof(connectByteArray1)];

然后你的委托(delegate)方法:

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

switch (streamEvent)
{
case NSStreamEventOpenCompleted:
{
DDLogVerbose(@"Stream opened");
break;
}

case NSStreamEventHasBytesAvailable:
{
if(!rawData) {
rawData = [[NSMutableData data] retain];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)theStream read:buf maxLength:1024];
if(len) {
[rawData initWithBytes:buf length:len];
} else {
DDLogVerbose(@"no buffer!");
}
}
case NSStreamEventErrorOccurred:
{
if ([theStream isKindOfClass:[NSInputStream class]]) {
NSString* address = [self getAddress];
NSString* myIPAdress = [NSString stringWithFormat:@"IP Address: %@", address];

//[cClient updateRequest];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cant Connect" message:[NSString stringWithFormat:@"Cant connect to server: %@, Make sure you are connected to the proper wireless network. Your Ip Address is %@",CCV.ipAddress,myIPAdress] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"Reconnect", nil];

[alert show];
[alert release];
}
break;
}

case NSStreamEventEndEncountered:
{
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[theStream release];
break;
}
case NSStreamEventHasSpaceAvailable:
{
//DDLogVerbose(@"has space available");
break;
}

case NSStreamEventNone:
{
DDLogVerbose(@"none");
break;
}

default:
{
DDLogVerbose(@"Unknown event");
}
}
}

可以看到有连接、未连接、断开连接的情况这就是你所需要的

关于objective-c - 如何检测网络断开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8332121/

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