在iOS中保持应用闲置一段时间后,SRWebsocket连接会自动关闭 [英] SRWebsocket connection is closing automatically after keeping app idle for sometime in iOS
问题描述
我正在使用SRWebSocket在iOS中打开Websocket连接.但是,如果有时我使应用程序保持空闲状态,则连接会自动关闭.之后,当我尝试发送任何数据时,websocket连接失败.
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.
在我手动断开连接之前,是否仍要保持websocket连接的活动状态?
Is there anyway to keep the websocket connection alive, until I manually disconnect?
推荐答案
我们需要间歇性ping服务器(以我为例,每30秒执行一次),以避免关闭服务器端的连接. /p>
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];
}
_webSocket 是我的SRWebSocket对象, _timer 是NSTimer的对象.
Where, _webSocket is my SRWebSocket object, _timer is an object of NSTimer.
这篇关于在iOS中保持应用闲置一段时间后,SRWebsocket连接会自动关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!