Cocos Creator 3.x 里的 SocketRocket 在iOS环境下很容易连接超时,导致反复断线重连。解决办法是增加一个NSTimer,定时发送ping消息,防止连接超时。
下面是增加了 NSTimer 的 WebSocketImpl类,在 WebSocket-apple.mm 中。
@implementation WebSocketImpl {
SRWebSocket *_ws;
cc::network::WebSocket *_ccws;
cc::network::WebSocket::Delegate *_delegate;
ccstd::string _url;
ccstd::string _selectedProtocol;
bool _isDestroyed;
NSTimer *timer;
}
- (id)initWithURL:(const ccstd::string &)url protocols:(NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates ws:(cc::network::WebSocket *)ccws delegate:(const cc::network::WebSocket::Delegate &)delegate {
if (self = [super init]) {
_ccws = ccws;
_delegate = const_cast<cc::network::WebSocket::Delegate *>(&delegate);
_url = url;
NSURL *nsUrl = [[NSURL alloc] initWithString:[[NSString