Objective c NSStream失去连接时如何重新连接?

Objective c NSStream失去连接时如何重新连接?,objective-c,cocoa-touch,sockets,nsstream,Objective C,Cocoa Touch,Sockets,Nsstream,我正在构建一个应用程序,用于监视用户的位置,并通过套接字将其发送到我们的服务器。 在应用程序启动时,应用程序将连接到服务器上的套接字,并且我们能够向服务器发送数据 但当用户从手机切换到wifi时,连接就会中断。我试图找出如何简单地重新连接(自动),但我不知道如何。有人能帮我吗 我现在使用的代码(LocationRecorder.m): // //位置记录器 // #导入“LocationRecorder.h” #进口 #进口 #进口 @实现位置记录器 @综合定位经理; NSInputStream

我正在构建一个应用程序,用于监视用户的位置,并通过套接字将其发送到我们的服务器。 在应用程序启动时,应用程序将连接到服务器上的套接字,并且我们能够向服务器发送数据

但当用户从手机切换到wifi时,连接就会中断。我试图找出如何简单地重新连接(自动),但我不知道如何。有人能帮我吗

我现在使用的代码(LocationRecorder.m):

//
//位置记录器
//
#导入“LocationRecorder.h”
#进口
#进口
#进口
@实现位置记录器
@综合定位经理;
NSInputStream*inputStream;
NSOutputStream*outputStream;
-(无效)启动日期
{
//这仅在应用程序启动时运行一次
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
locationManager.desiredAccuracy=KCallocationAccuracyBestforNavigation;
[locationManager startUpdatingLocation];
[locationManager startUpdatingHeading];
//连接到插座
[自启动网络通信];
//每5秒设置一个计时器
[NSTimer scheduledTimerWithTimeInterval:5
目标:自我
选择器:@selector(timerInterval:)
用户信息:无
重复:是];
}
-(void)timerInterval:(NSTimer*)计时器
{
CLLocation*location=[locationManager位置];
//处理位置数据
[自处理位置数据:位置];
}
-(void)processLocationData:(CLLocation*)位置
{
//格式化所有数据以准备将其发送到服务器
NSString*响应=[NSString stringWithFormat:stringFormat,
utctime,
utcdate,
拉特,
液化天然气,
中高音,
速度
标题
伊梅,
努姆萨特,
电池,
cellno];
//NSLog(@“%@”,@“tx”);
NSData*data=[[NSData alloc]initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
//检查连接
如果([OutputStreamStatus]!=NSStreamStatus打开){
NSLog(@“%@”,“重新连接…”);
[输出流打开];
}
[outputStream写入:[数据字节]最大长度:[数据长度]];
}
-(无效)网络通信
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL,(CFStringRef)@“********”,9000,&readStream,&writeStream);
outputStream=(NSOutputStream*)writeStream;
//我们不初始化inputStream,因为我们不需要输入流(服务器(还)不回话)
[outputStream setDelegate:self];
[outputStream ScheduleRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];
[输出流打开];
}
-(void)流:(NSStream*)流手柄通风口:(NSStreamEvent)流通风口
{
开关(排气口)
{
案例1:文通:
//无法连接到主机,未触发任何事件
打破
已完成的案例:
//连接!
NSLog(@“%@”,“连接到套接字”);
打破
发生错误的案例:
//连接问题
NSLog(@“%@”,“连接丢失”);
[theStream open];//这不起作用:-(
打破
案件被驳回:
//连接关闭
[溪流关闭];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];
[theStream release];
流=零;
打破
违约:
//未知或未跟踪的事件
打破
}
}
@结束

感谢Martin R的简单解决方案

我将
[outputStream close]
添加到了NSStreamVenterRoccurred,在将数据发送到processLocationData中的套接字之前,我添加了以下代码:

// check for connection
if ([outputStream streamStatus] != NSStreamStatusOpen) {
    NSLog(@"reconnecting...", nil);
    [self initNetworkCommunication];
}

您需要保持连接的状态。当您想写入服务器并且断开连接时,您需要重新连接。我认为这很简单?请参阅上面我更改的代码。这是我能想到的唯一方法,但这不起作用。我假设您必须在出现网络错误的情况下关闭流,然后重新打开它再次调用
initNetworkCommunication
。谢谢,成功了。这似乎对我不起作用。你还需要做其他事情吗?
// check for connection
if ([outputStream streamStatus] != NSStreamStatusOpen) {
    NSLog(@"reconnecting...", nil);
    [self initNetworkCommunication];
}