在iOS中保持app空闲一段时间后,SRWebsocket连接自动关闭

时间:2015-12-10 09:46:01

标签: ios websocket socketrocket

我正在使用SRWebSocket在iOS中打开websocket连接。但是,如果我有时保持应用程序空闲,则连接自动关闭。之后,当我尝试发送任何数据时,websocket连接失败。

无论如何都要保持websocket连接活着,直到我手动断开连接?

2 个答案:

答案 0 :(得分:3)

我们需要间歇性地ping服务器(在我的情况下,我每隔30秒执行一次),以避免从服务器端关闭连接。

- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
    NSLog(@"Websocket Connected");

    // Sending autoping to server
    [self startConnectionCheckTimer];
}

// Checking for WSconnection by Sending Scheduled Ping
- (void)startConnectionCheckTimer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:30.0f
                                                  target:self
                                                selector:@selector(sendPing:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}

- (void)stopConnectionCheckTimer {
    if ([_timer isValid]) {
        [_timer invalidate];
    }
    _timer = nil;
}

- (void)sendPing:(id)sender
{
    [_webSocket sendPing:nil];
}

其中, _webSocket 是我的SRWebSocket对象,         _timer 是NSTimer的对象。

答案 1 :(得分:2)

当应用程序处于空闲状态或应用程序进入后台时,Web Socket会断开连接。您可以尝试使用此:
[UIApplication sharedApplication] .idleTimerDisabled = YES

使用此功能,如果您的应用正在运行,则会禁用iPhone的闲置状态。

相关问题