socketcluster-client-swift
使用 Swift 编写的本地 iOS/macOS 客户端
概述
此客户端提供以下功能:
- 易于设置和使用
- 支持发送和监听远程事件
- 发布/订阅
- 身份验证(JWT)
客户端支持以下平台:
- iOS >= 8.0
- macOS >= 10.10
- watchOS >= 2.0
- tvOS >= 9.0
安装和使用
CocoaPods
pod 'ScClient'
Swift 包管理器
- 要安装,请将以下内容添加到 Package.swift 的依赖性部分
dependencies: [
// other dependencies
.package(url: "https://github.com/sacOO7/ScClient", from: "2.0.0")
]
- 要使用库,请将以下内容添加到目标依赖项中
targets: [
.target(
name: "tool",
dependencies: [
"ScClient"
])
]
描述
通过传递 socketcluster-server 的端点 URL 来创建 scclient
实例
//Create a client instance
var client = ScClient(url: "https://:8000/socketcluster/")
重要提示:socketcluster 端点的默认 URL 总是 ws://somedomainname.com/socketcluster/。
注册基本监听器
- 将不同的闭包函数作为参数传递给注册监听器
- 示例:main.swift
import Foundation
import ScClient
var client = ScClient(url: "https://:8000/socketcluster/")
var onConnect = {
(client :ScClient) in
print("Connnected to server")
}
var onDisconnect = {
(client :ScClient, error : Error?) in
print("Disconnected from server due to ", error?.localizedDescription)
}
var onAuthentication = {
(client :ScClient, isAuthenticated : Bool?) in
print("Authenticated is ", isAuthenticated)
startCode(client : client)
}
var onSetAuthentication = {
(client : ScClient, token : String?) in
print("Token is ", token)
}
client.setBasicListener(onConnect: onConnect, onConnectError: nil, onDisconnect: onDisconnect)
client.setAuthenticationListener(onSetAuthentication: onSetAuthentication, onAuthentication: onAuthentication)
client.connect()
while(true) {
RunLoop.current.run(until: Date())
usleep(10)
}
func startCode(client scclient.Client) {
// start writing your code from here
// All emit, receive and publish events
}
连接到服务器
- 要连接到服务器:
//This will send websocket handshake request to socketcluster-server
client.connect()
获取连接状态
//This will send websocket handshake request to socketcluster-server
var status = client.isConnected()
发出和监听事件
事件发射器
- 事件名是事件名称,消息可以是字符串、布尔值、整数或对象。
client.emit(eventName: eventname, data: message as AnyObject)
//client.emit(eventName: "chat", data: "This is my sample message" as AnyObject)
- 用于发送带有确认的事件
client.emitAck(eventName: "chat", data: "This is my sample message" as AnyObject, ack : {
(eventName : String, error : AnyObject? , data : AnyObject?) in
print("Got data for eventName ", eventName, " error is ", error, " data is ", data)
})
事件监听器
- 用于监听事件
接收到的对象可以是字符串、布尔值、整数或对象
// Receiver code without sending acknowledgement back
client.on(eventName: "yell", ack: {
(eventName : String, data : AnyObject?) in
print("Got data for eventName ", eventName, " data is ", data)
})
- 用于向服务器发送确认
// Receiver code with ack
client.onAck(eventName: "yell", ack: {
(eventName : String, data : AnyObject?, ack : (AnyObject?, AnyObject?) -> Void) in
print("Got data for eventName ", eventName, " data is ", data)
ack("This is error " as AnyObject, "This is data " as AnyObject)
})
通过频道实现发布-订阅
创建频道
- 用于创建和订阅频道
// without acknowledgement
client.subscribe(channelName: "yell")
//with acknowledgement
client.subscribeAck(channelName: "yell", ack : {
(channelName : String, error : AnyObject?, data : AnyObject?) in
if (error is NSNull) {
print("Successfully subscribed to channel ", channelName)
} else {
print("Got error while subscribing ", error)
}
})
在频道上发布事件
- 用于发布事件
// without acknowledgement
client.publish(channelName: "yell", data: "I am sending data to yell" as AnyObject)
// with acknowledgement
client.publishAck(channelName: "yell", data: "I am sending data to yell" as AnyObject, ack : {
(channelName : String, error : AnyObject?, data : AnyObject?) in
if (error is NSNull) {
print("Successfully published to channel ", channelName)
}else {
print("Got error while publishing ", error)
}
})
监听频道
- 用于监听频道事件
client.onChannel(channelName: "yell", ack: {
(channelName : String , data : AnyObject?) in
print ("Got data for channel", channelName, " object data is ", data)
})
取消频道订阅
// without acknowledgement
client.unsubscribe(channelName: "yell")
//with acknowledgement
client.unsubscribeAck(channelName: "yell", ack : {
(channelName : String, error : AnyObject?, data : AnyObject?) in
if (error is NSNull) {
print("Successfully unsubscribed to channel ", channelName)
} else {
print("Got error while unsubscribing ", error)
}
})
禁用SSL证书验证
var client = ScClient(url: "https://:8000/socketcluster/")
client.disableSSLVerification(true)
自定义队列
在调用代理方法时可以指定自定义队列。默认情况下使用 DispatchQueue.main
,这意味着所有代理方法调用都在主线程上运行。需要注意的是,所有WebSocket处理都在后台线程上完成,只有修改队列时才会更改代理方法调用。实际处理总是在后台线程上进行,不会暂停您的应用程序。
var client = ScClient(url: "https://:8000/socketcluster/")
//create a custom queue
client.setBackgroundQueue(queueName : "com.example.chatapp")
自定义头部
您还可以使用以下方式重写默认WebSocket头部,使用您自己的自定义头部:
var request = URLRequest(url: URL(string: "https://:8000/socketcluster/")!)
request.timeoutInterval = 5
request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol")
request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version")
request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header")
var client = ScClient(URLRequest: request)
自定义HTTP方法
您的服务器在连接到websocket时可能使用不同的HTTP方法。
var request = URLRequest(url: URL(string: "https://:8000/socketcluster/")!)
request.httpMethod = "POST"
request.timeoutInterval = 5
var client = ScClient(URLRequest: request)
协议
如果需要指定协议,简单地在初始化时添加即可。
//chat and superchat are the example protocols here
var request = URLRequest(url: URL(string: "https://:8000/socketcluster/")!)
var client = ScClient(URLRequest: request, protocols: ["chat","superchat"])