iOS WebSocket教程

Swift国内社区: SwiftMic


Swift版本: 4.1

简介

通过 WebSocket 可以实现保持长连接。

WebSocket第三方库

Starscream

开始

编辑 Podfile

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

target 'Your target' do
    pod 'Starscream'
end

执行 pod install

创建 WebSocket 对象

mWebSocket = WebSocket(url: URL(string: "ws://localhost:8080/")!)

设置委托对象

mWebSocket.delegate = self

这里需要实现 WebSocketDelegate 协议

/// 连接成功后的回调
func websocketDidConnect(socket: WebSocketClient) {
    print("websocketDidConnect")
}

/// 断开连接后的回调    
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
    print("websocketDidDisconnect, error = \(String(describing: error))")
}

/// 接收到消息后的回调(String)    
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
    print("websocketDidReceiveMessage, text = \(text)")
        
    if text.contains("Hello Client") {
        // 发送消息
        mWebSocket.write(string: "Send msg from iOS Client by Cary")
    }
 }

/// 接收到消息后的回调(Data)    
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
    print("websocketDidReceiveData")
}

接下来进行 connect 操作

mWebSocket.connect()

断开连接操作

if mWebSocket.isConnected {
    mWebSocket.disconnect()
}

WebSocket Server

Starscream 自带了个 Server 端的WebSocket示例,地址是 https://github.com/daltoniam/Starscream/tree/master/examples/SimpleTest。

按照对应的 README.md 操作即可。

Demo源码

https://github.com/CaryZheng/iOSTutorials

你可能感兴趣的:(iOS WebSocket教程)