SwiftStomp |
---|
![]() |
![]() |
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)
如果您更习惯使用 Combine
发布者而不是代理,SwiftStomp 可以通过上游 (upstreams) 报告所有 event
、message
和 receiptId
。当您想在 SwiftUI 项目中使用 SwiftStomp 时,此功能尤其突出。请查看示例项目,了解如何在 SwiftUI 项目中使用上游 (upstreams)。
// ** Subscribe to events: [Connect/Disconnect/Errors]
swiftStomp.eventsUpstream
.receive(on: RunLoop.main)
.sink { event in
switch event {
case let .connected(type):
print("Connected with type: \(type)")
case .disconnected(_):
print("Disconnected with type: \(type)")
case let .error(error):
print("Error: \(error)")
}
}
.store(in: &subscriptions)
// ** Subscribe to messages: [Text/Data]
swiftStomp.messagesUpstream
.receive(on: RunLoop.main)
.sink { message in
switch message {
case let .text(message, messageId, destination, _):
print("\(Date().formatted()) [id: \(messageId), at: \(destination)]: \(message)\n")
case let .data(data, messageId, destination, _):
print("Data message with id `\(messageId)` and binary length `\(data.count)` received at destination `\(destination)`")
}
}
.store(in: &subscriptions)
// ** Subscribe to receipts: [Receipt IDs]
swiftStomp.receiptUpstream
.sink { receiptId in
print("SwiftStop: Receipt received: \(receiptId)")
}
.store(in: &subscriptions)
完整的 Connect
签名
self.swiftStomp.connect(timeout: 5.0, acceptVersion: "1.1,1.2")
如果您希望在任何意外断开连接后重新连接,请启用 autoReconnect
属性。
self.swiftStomp.autoReconnect = true
注意:如果您使用
disconnect()
函数手动断开连接,并且启用了autoReconnect
,则套接字将在断开连接后尝试重新连接。 如果这不是您想要的,请在调用disconnect()
之前禁用autoReconnect
。
完整的 Subsribe
签名。 请注意,只有在确保已连接到 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")
}
您可以控制发送 WebSocket 'Ping' 消息。 完整签名如下
func ping(data: Data = Data(), completion: (() -> Void)? = nil)
您将收到 'Pong' 消息作为响应。
如果您想确保您的连接仍然有效,您可以使用“自动 Ping”功能。 完整签名如下
func enableAutoPing(pingInterval: TimeInterval = 10)
在从上次发送 sendFrame
命令(例如:connect
、ack
、send
....)经过 pingInterval
时间后,“自动 Ping”功能会将 ping
命令发送到 websocket 服务器。
注意:默认情况下,自动 Ping 已禁用。 因此,您必须在连接到服务器后启用它。 另请注意,如果您与服务器断开连接或显式调用
disconnect()
,则必须再次调用enableAutoPing()
。
要禁用“自动 Ping”功能,请使用 disableAutoPing()
。
此示例已使用 Spring Boot websocket 服务器和 RabbitMQ 作为外部消息代理进行测试。
请参考示例了解更多功能
要运行示例项目,请克隆存储库,然后首先从 Example 目录运行 pod install
。
SwiftStomp 可通过 CocoaPods 获得。 要安装它,只需将以下行添加到您的 Podfile
pod 'SwiftStomp'
从 Xcode 11 开始,您可以使用 Swift 包管理器 将 SwiftStomp 添加到您的项目。
https://github.com/Romixery/SwiftStomp.git
。Ahmad Daneshvar, romixery@gmail.com
非常感谢:@stuartcamerondeakin, @hunble, @aszter
SwiftStomp 在 MIT 许可下可用。 有关更多信息,请参见 LICENSE 文件。