SwiftStomp
Starscream WebSocket 库。
一个优雅的 Swift Stomp 客户端,基于特性
- 易于设置,非常轻量级
- 支持所有 STOMP V1.2 框架。CONNECT、SUBSCRIBE、RECEIPT 等。
- 自动使用原生 JSON
Encoder
进行对象序列化。 - 发送和接收
Data
和Text
- 自动重连
- 日志记录
使用
设置
以最少的条件快速初始化
let url = URL(string: "ws://192.168.88.252:8081/socket")!
self.swiftStomp = SwiftStomp(host: url) //< Create instance
self.swiftStomp.delegate = self //< Set delegate
self.swiftStomp.autoReconnect = true //< Auto reconnect on error or cancel
self.swiftStomp.connect() //< Connect
委托
实现所有委托方法以处理所有STOMP事件!
func onConnect(swiftStomp : SwiftStomp, connectType : StompConnectType)
func onDisconnect(swiftStomp : SwiftStomp, disconnectType : StompDisconnectType)
func onMessageReceived(swiftStomp: SwiftStomp, message: Any?, messageId: String, destination: String, headers : [String : String])
func onReceipt(swiftStomp : SwiftStomp, receiptId : String)
func onError(swiftStomp : SwiftStomp, briefDescription : String, fullDescription : String?, receiptId : String?, type : StompErrorType)
连接
完整的 Connect
签名
self.swiftStomp.connect(timeout: 5.0, acceptVersion: "1.1,1.2")
如果您希望在任何意外断开连接后重新连接,请启用 autoReconnect
属性。
self.swiftStomp.autoReconnect = true
注意事项: 如果您使用
disconnect()
函数手动断开连接,并且autoReconnect
已启用,则套接字将在断开连接后尝试重新连接。如果您不希望这样做,请在调用disconnect()
之前禁用autoReconnect
。
订阅
完整的 Subscribe
签名。请注意,仅在确保连接到STOMP后进行订阅。我建议在 onConnect
委托中使用 connectType == .toStomp
进行订阅。
swiftStomp.subscribe(to: "/topic/greeting", mode: .clientIndividual)
发送消息
您可以对发送消息进行完全控制。完整的签名如下
swiftStomp.send(body: "This is message's text body", to: "/app/greeting", receiptId: "msg-\(Int.random(in: 0..<1000))", headers: [:])
检查连接状态
您可以使用 connectionStatus
属性检查SwiftStomp的状态。
switch self.swiftStomp.connectionStatus {
case .connecting:
print("Connecting to the server...")
case .socketConnected:
print("Scoket is connected but STOMP as sub-protocol is not connected yet.")
case .fullyConnected:
print("Both socket and STOMP is connected. Ready for messaging...")
case .socketDisconnected:
print("Socket is disconnected")
}
手动Ping
您控制发送WebSocket 'Ping'消息。完整签名如下
func ping(data: Data = Data(), completion: (() -> Void)? = nil)
您将收到响应的消息'Pong'。
自动Ping
如果您想确保您的连接仍然活跃,可以使用'自动Ping'功能。完整签名如下
func enableAutoPing(pingInterval: TimeInterval = 10)
'autoPing'功能,将在从上次发送的sendFrame
命令(例如:connect
,ack
,send
...等)过去pingInterval
时间后向WebSocket服务器发送ping
命令。
注意:自动Ping默认是禁用的。因此,您需要连接到服务器后启用它。另外,请考虑,如果您从服务器断开连接或显式调用
disconnect()
,您必须再次调用enableAutoPing()
。
要禁用'自动Ping'功能,请使用disableAutoPing()
。
测试环境
此示例使用与Spring Boot websocket服务器及RabbitMQ作为外部消息代理进行了测试。
示例
请参阅示例以获取更多功能
要运行示例项目,首先请将仓库克隆,然后从示例目录中运行pod install
。
需求
- iOS 10 或更高版本
安装
CocoaPods
SwiftStomp 可通过 CocoaPods 获取。要安装它,只需在 Podfile 中添加以下行
pod 'SwiftStomp'
Swift 包管理器
从 Xcode 11 开始,您可以使用 Swift 包管理器 将 SwiftStomp 添加到您的项目中。
- 选择文件 > Swift 包 > 添加包依赖。在“选择包仓库”对话框中输入
https://github.com/Romixery/SwiftStomp.git
- 在下一页中,指定版本解析规则为“下次主版本”,并将其最早版本指定为“1.0.4”。
- 在 Xcode 确认源和解析版本后,您可以选择“SwiftStomp”库并将其添加到您的应用程序目标中。
作者
Ahmad Daneshvar, [email protected]
许可证
SwiftStomp 在 MIT 许可证下提供。有关更多信息,请参阅 LICENSE 文件。