Swift WebSocket 重连问题,并判断网络情况

在上一篇文章中,已经说明如何在Swift下集成WebScoket
但是,WebSocket总是绕不开重连问题,比如手机突然断网,app进入睡眠模式等等

以下是重连方法,在socket单例文件中


import Starscream
import Reachability

let webSocket = WebSocketSingle.shared
var reConnectTime = 0 //设置重连次数
let reachability = Reachability()! //判断网络连接
let hudProgress = AnimateView()

final class WebSocketSingle:NSObject,WebSocketDelegate {
    
    func websocketDidConnect(socket: WebSocketClient) {
         //设置重连次数,解决无限重连问题
        reConnectTime = 0
    }
    
    func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
        //执行重新连接方法
        socketReconnect()
    }
    
    func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
    }
    
    func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
        print(" WebSocketSingle DidReceiveMessage data:",data)
    }
    
    
    //构造单例数据
    static let shared = WebSocketSingle()
    
    private override init() {
    }
   
}


      //socket 重连逻辑
    func socketReconnect() {
        //判断网络情况,如果网络正常,可以执行重连
        if reachability.connection != .none {
            //设置重连次数,解决无限重连问题
            reConnectTime =  reConnectTime + 1
            if reConnectTime < 5 {
                //添加重连延时执行,防止某个时间段,全部执行
                let time: TimeInterval = 2.0
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
                    if !SingletonSocket.sharedInstance.socket.isConnected {
                        SingletonSocket.sharedInstance.socket.connect()
                        SingletonSocket.sharedInstance.socket.disconnect()
                    }
                }
            } else {
                //提示重连失败
            }
        } else {
            //提示无网络
        }
    }

//socket主动断开,放在app进入后台时,数据进入缓存。app再进入前台,app出现卡死的情况
    func socketDisConnect() {
        if SingletonSocket.sharedInstance.socket.isConnected {
            SingletonSocket.sharedInstance.socket.disconnect()
        }
    }

然后是使用,放在Appdelegate文件中

//进入后台模式,主动断开socket,防止出现处理不了的情况

func applicationWillResignActive(_ application: UIApplication) {
       if WebSocketSingle.SingletonSocket.sharedInstance.socket.isConnected {
            reConnectTime = 5
            webSocket.socketDisConnect()
        }
 }

//进入前台模式,主动连接socket
    func applicationDidBecomeActive(_ application: UIApplication) {
        //解决因为网络切换或链接不稳定问题,引起socket断连问题
        //如果app从无网络,到回复网络,需要执行重连
        if !WebSocketSingle.SingletonSocket.sharedInstance.socket.isConnected {
            reConnectTime = 0
            webSocket.socketReconnect()
        }
    }

你可能感兴趣的:(Swift WebSocket 重连问题,并判断网络情况)