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?
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.
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.