【问题标题】:SRWebsocket connection is closing automatically after keeping app idle for sometime in iOS在iOS中保持应用程序空闲一段时间后,SRWebsocket连接会自动关闭
【发布时间】:2015-12-11 17:44:35
【问题描述】:

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

在我手动断开连接之前,是否有办法让 websocket 连接保持活动状态?

【问题讨论】:

    标签: ios websocket socketrocket


    【解决方案1】:

    我们需要间歇性地 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 的一个对象。

    【讨论】:

      【解决方案2】:

      当应用程序保持空闲或应用程序进入后台时,Web Socket 会断开连接。你可以试试这个:
      [UIApplication sharedApplication].idleTimerDisabled = YES

      如果您的应用正在运行,则使用此选项将禁用将 iPhone 设置为空闲。

      【讨论】:

      • 我用它来防止 websocket 连接从客户端关闭。感谢您的回复。
      • @NobinThomas:如果这个答案对你有用,那么请 +1。如果您有任何其他问题,我很乐意为您提供帮助。
      • 嗨,Neha,不幸的是,我没有那么高的声誉来加分(显示至少需要 15 分)。 :( 获得该特权后,我将添加。感谢您的回复。
      • 另外,从文档中我了解到,您应该仅在必要时设置此属性,并确保在不再需要时将其重置为 NO。唯一应该禁用空闲计时器的应用程序是映射应用程序、游戏或程序,在这些应用程序需要在用户交互最少的情况下继续显示内容。参考:developer.apple.com/library/ios/documentation/UIKit/Reference/…。这就是我选择上述选项的原因。
      • 它对于在后台检查推送通知的应用程序(例如 Facebook)也很有用。
      猜你喜欢
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      相关资源
      最近更新 更多