gpt4 book ai didi

ios - 在 iOS 中保持应用程序空闲一段时间后,SRWebsocket 连接自动关闭

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:21:09 24 4
gpt4 key购买 nike

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

在我手动断开连接之前,有没有办法保持 websocket 连接?

最佳答案

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

关于ios - 在 iOS 中保持应用程序空闲一段时间后,SRWebsocket 连接自动关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34198427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com