SRWebsocket connection is closing automatically after keeping app idle for sometime in iOS

依然范特西╮ 提交于 2019-12-20 02:29:45

问题


I am using SRWebSocket to open a websocket connection in iOS. But if I am keeping the application idle for sometimes, the connection is closing automatically. After that when I am trying to send any data, the websocket connection is failing.

Is there anyway to keep the websocket connection alive, until I manually disconnect?


回答1:


We need to ping the server intermittently (In my case, I do this in every 30 seconds), for avoiding to close the connection from the server side.

- (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];
}

Where, _webSocket is my SRWebSocket object, _timer is an object of NSTimer.




回答2:


Web Socket gets disconnected when the app is kept idle or when the app goes in background. You can try using this:
[UIApplication sharedApplication].idleTimerDisabled = YES

Using this, will disable the provision of iPhone to be idle if your app is running.



来源:https://stackoverflow.com/questions/34198427/srwebsocket-connection-is-closing-automatically-after-keeping-app-idle-for-somet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!