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