本文主要是介绍[Swift 开发] 一分钟会用Web Socket,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一般网络请求时,只能client发请求,server回答。server不能主动给client发消息,Web Socket就能解决这个问题。
1.导入框架
import Starscream
2.初始化对象
var socket: WebSocket?
var isConnected = false
let serverUrl = "ws://82.157.123.54:9010/ajaxchattest"var request = URLRequest(url: URL(string: serverUrl)!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket?.delegate = self
socket?.connect()
3.接收消息和回调结果
func didReceive(event: WebSocketEvent, client: WebSocket) {switch event {case let .connected(headers):isConnected = trueprint("websocket is connected: \(headers)")case let .disconnected(reason, code):isConnected = falseprint("websocket is disconnected: \(reason) with code: \(code)")case let .text(string):label.text = stringprint("Received text: \(string) \(CFAbsoluteTimeGetCurrent())")case let .binary(data):print("Received data: \(data.count)")case .ping:print("ping")breakcase .pong:print("pong \(CFAbsoluteTimeGetCurrent())")breakcase .viabilityChanged:breakcase .reconnectSuggested:breakcase .cancelled:isConnected = falseprint("断开链接")case .error:isConnected = falseprint("error")}}
4.测试
@IBAction func sendClicked(_ sender: Any) {socket?.write(data: "1234".data(using: .utf8)!, completion: {print("发送完成")}) }//发送完成
//Received text: 1234
@IBAction func sendClicked(_ sender: Any) {socket?.write(string: "Hi Server! \(CFAbsoluteTimeGetCurrent())")socket?.write(ping: Data())
}//Received text: Hi Server!
//pong 660204472.596506
这篇关于[Swift 开发] 一分钟会用Web Socket的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!