iOS第三方框架使用技巧

iOS 接入WebSocket

2018-06-23  本文已影响491人  FicowShen

WebSocket是什么

WebSocket协议是 基于TCP 的一种网络协议。
它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。

websocket与http的区别



WebSocket基本原理

帧协议:

      0                   1                   2                   3
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
     +-+-+-+-+-------+-+-------------+-------------------------------+
     |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
     |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
     |N|V|V|V|       |S|             |   (if payload len==126/127)   |
     | |1|2|3|       |K|             |                               |
     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
     |     Extended payload length continued, if payload len == 127  |
     + - - - - - - - - - - - - - - - +-------------------------------+
     |                               |Masking-key, if MASK set to 1  |
     +-------------------------------+-------------------------------+
     | Masking-key (continued)       |          Payload Data         |
     +-------------------------------- - - - - - - - - - - - - - - - +
     :                     Payload Data continued ...                :
     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
     |                     Payload Data continued ...                |
     +---------------------------------------------------------------+



连接过程示意图

其他特点包括:
(1)建立在 TCP 协议之上,服务器端的实现比较容易。
(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
(3)数据格式比较轻量,性能开销小,通信高效。
(4)可以发送文本,也可以发送二进制数据。
(5)没有同源限制,客户端可以与任意服务器通信。
(6)协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。



WebSocket常见的使用场景

要求服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息。(也可以采用HTTP/2)



iOS端实现WebSocket连接的参考方案

SocketRocket

SocketRocket是facebook封装的websocket开源库,采用纯Objective-C编写。
使用者需要自己实现心跳机制,以及适配断网重连等情况。

SocketIO

SocketIO将WebSocket、AJAX和其它的通信方式全部封装成了统一的通信接口,也就是说,我们在使用SocketIO时,不用担心兼容问题,底层会自动选用最佳的通信方式。因此说,WebSocket是SocketIO的一个子集。
另外,如果后端采用的是原生WebSocket,不建议大家使用SocketIO。
因为SocketIO定制了专有的协议,并不是纯粹的WebSocket,可能会遭遇适配问题。
不过,SocketIO的API极其易用!!!

Starscream

采用Swift编写,不过笔者暂时还没有用过,不发表任何评论。



iOS端利用SocketRocket实现WebSocket连接



示例代码如下,欢迎指正:

import Foundation
import SocketRocket
import Alamofire

/// Websocket连接中的通知
let FSWebSocketConnectingNotification = NSNotification.Name.init("FSWebSocketConnectingNotification")
/// Websocket连接成功的通知
let FSWebSocketDidOpenNotification = NSNotification.Name.init("FSWebSocketDidOpenNotification")
/// Websocket连接收到新消息的通知
let FSWebSocketDidReceiveMessageNotification = NSNotification.Name.init("FSWebSocketDidReceiveMessageNotification")
/// Websocket连接失败的通知
let FSWebSocketFailWithErrorNotification = NSNotification.Name.init("FSWebSocketFailWithErrorNotification")
/// Websocket连接已关闭的通知
let FSWebSocketDidCloseNotification = NSNotification.Name.init("FSWebSocketDidCloseNotification")

/// websocket连接地址,请输入有效的websocket地址!
let WSAddr = "ws://host:port/ws"

/// 心跳包发送间隔,3分钟
let PingDuration = 180

/// Websocket连接对象
class FSWebsocket: NSObject,SRWebSocketDelegate {
    
    static let `default` = FSWebsocket.init()
    /// 是否在断开连接后自动重连
    var autoReconnect = true
    
    private var reachabilityManager = NetworkReachabilityManager.init(host: "www.baidu.com")
    /// websocket连接地址
    private var addr = WSAddr
    /// websocket连接
    private var ws:SRWebSocket?
    /// 心跳包定时发送计时器
    private var heartbeatTimer:Timer?
    /// 重连计数器
    private var reconnectCount = 0
    
    override init() {
        super.init()
        
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
        
        // 切换网络自动重连
        reachabilityManager?.listener = { [weak self] (networkReachabilityStatus) in
            // 正在连接中或已经连接成功,不需要重连
            if self?.ws?.readyState == .CONNECTING || self?.ws?.readyState == .OPEN{
                return
            }
            // 设置自动重连才会进行自动重连
            if let s = self, s.autoReconnect{
                self?.reconnect()
            }
        }
        reachabilityManager?.startListening()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func appDidEnterBackground(){
        
        close()
    }
    @objc func appWillEnterForeground(){
        
        reconnect()
    }
    
    // MARK: - Send Message
    
    @discardableResult
    func sendJSON(_ json:[AnyHashable : Any]) -> NSError?{
        let jsonData = try? JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
        return self.sendData(jsonData)
    }
    
    @discardableResult
    func sendData(_ data:Data?) -> NSError?{
        
        guard ws?.readyState == SRReadyState.OPEN else{
            return NSError.init(domain: "FSWebsocket", code: SRStatusCodeGoingAway.rawValue, userInfo: nil)
        }
        ws?.send(data)
        return nil
    }
    
    // MARK: - Connection Management
    
    /// 连接websocket服务器
    func open(){
        
        let url = URL(string: self.addr)
        assert(url != nil)
        
        self.ws = SRWebSocket.init(url: url!)
        ws?.delegate = self
        ws?.open()
        NotificationCenter.default.post(name: FSWebSocketConnectingNotification, object: self)
    }
    
    /// 重新连接
    private func reconnect(){
        
        if !autoReconnect{
            return
        }
        if reconnectCount > 64 {
            return
        }
        
        let seconds = DispatchTime.now().uptimeNanoseconds + UInt64(reconnectCount) * NSEC_PER_SEC
        let time = DispatchTime.init(uptimeNanoseconds: seconds)
        DispatchQueue.main.asyncAfter(deadline: time) {
            self.ws?.close()
            self.ws = nil
            
            self.open()
        }
        
        if reconnectCount == 0 {
            reconnectCount = 1
        }
        reconnectCount *= 2
    }
    
    /// 关闭连接
    func close(){
        
        self.destroyHeartbeat()
        
        self.ws?.close()
        self.ws = nil
        
        resetConnectCount()
    }
    
    /// 发送心跳包
    @objc func heartbeat(){
        
        guard ws?.readyState == SRReadyState.OPEN else{
            return
        }
        self.ws?.sendPing(nil)
    }
    /// 启动心跳
    private func startHeartbeat(){
        
        let timer = Timer.init(timeInterval: TimeInterval(PingDuration), target: self, selector: #selector(heartbeat), userInfo: nil, repeats: true)
        self.heartbeatTimer = timer
        RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
    }
    /// 停止心跳
    private func destroyHeartbeat(){
        
        self.heartbeatTimer?.invalidate()
        self.heartbeatTimer = nil
    }
    /// 重置重连尝试次数
    private func resetConnectCount(){
        
        reconnectCount = 0
    }
    
    
    // MARK: - SRWebSocketDelegate
    
    func webSocketDidOpen(_ webSocket: SRWebSocket!) {
        
        self.resetConnectCount()
        self.startHeartbeat()
        NotificationCenter.default.post(name: FSWebSocketDidOpenNotification, object: self)
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
        
        guard let msgString = message as? NSString else{
            return
        }
        guard let msgData = msgString.data(using: String.Encoding.utf8.rawValue) else{
            return
        }
        // 如果传输的是JSON数据,可以使用JSONSerialization将JSON字符串转换为字典
        guard let msgJSON = try? JSONSerialization.jsonObject(with: msgData, options: JSONSerialization.ReadingOptions.allowFragments) else{
            return
        }
        NotificationCenter.default.post(name: FSWebSocketDidReceiveMessageNotification, object: self, userInfo: ["message":msgJSON])
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {

        NotificationCenter.default.post(name: FSWebSocketFailWithErrorNotification, object: self, userInfo: ["error": error])
        // 连接失败:
        if (error as NSError).code == 50{
            // 断网,不重连
            return
        }
        // 当前页面不需要使用websocket,不重连
        // 重连次数超过限制,不重连
        reconnect()
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didReceivePong pongPayload: Data!) {
        // 心跳包响应回调
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
        
        // 连接被关闭
        NotificationCenter.default.post(name: FSWebSocketDidCloseNotification, object: self, userInfo: ["code": code, "reason": reason, "wasClean": wasClean])
        
        close()
    }
}




参考资料:
WebSocket 教程
iOS websocket接入
[iOS] 接入WebSocket记录 + 一些个人经验
解读 JavaScript 之深入探索 WebSockets 和 HTTP/2
IETF Tools - The WebSocket Protocol

上一篇下一篇

猜你喜欢

热点阅读