SwiftStomp

一个优雅的 Swift STOMP 客户端,基于 iOS 的 URLSessionWebSocketTask

Version License Platform

SwiftStomp

目录

特性

用法

设置

快速初始化,只需最少的要求

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)

上游 (Upstreams)

如果您更习惯使用 Combine 发布者而不是代理,SwiftStomp 可以通过上游 (upstreams) 报告所有 eventmessagereceiptId。当您想在 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")
}

手动 Ping

您可以控制发送 WebSocket 'Ping' 消息。 完整签名如下

func ping(data: Data = Data(), completion: (() -> Void)? = nil)

您将收到 'Pong' 消息作为响应。

自动 Ping

如果您想确保您的连接仍然有效,您可以使用“自动 Ping”功能。 完整签名如下

func enableAutoPing(pingInterval: TimeInterval = 10)

在从上次发送 sendFrame 命令(例如:connectacksend ....)经过 pingInterval 时间后,“自动 Ping”功能会将 ping 命令发送到 websocket 服务器。

注意:默认情况下,自动 Ping 已禁用。 因此,您必须在连接到服务器后启用它。 另请注意,如果您与服务器断开连接或显式调用 disconnect(),则必须再次调用 enableAutoPing()

要禁用“自动 Ping”功能,请使用 disableAutoPing()

测试环境

此示例已使用 Spring Boot websocket 服务器和 RabbitMQ 作为外部消息代理进行测试。

示例

请参考示例了解更多功能

要运行示例项目,请克隆存储库,然后首先从 Example 目录运行 pod install

要求

安装

CocoaPods

SwiftStomp 可通过 CocoaPods 获得。 要安装它,只需将以下行添加到您的 Podfile

pod 'SwiftStomp'

Swift 包管理器

从 Xcode 11 开始,您可以使用 Swift 包管理器 将 SwiftStomp 添加到您的项目。

  1. 选择 File > Swift Packages > Add Package Dependency。 在“Choose Package Repository”对话框中输入 https://github.com/Romixery/SwiftStomp.git
  2. 在下一页中,将版本解析规则指定为“Up to Next Major”,并以“1.0.4”作为最早版本。
  3. 在 Xcode 检出源代码并解析版本后,您可以选择“SwiftStomp”库并将其添加到您的应用程序目标。

作者

Ahmad Daneshvar, romixery@gmail.com

贡献者

非常感谢:@stuartcamerondeakin, @hunble, @aszter

许可

SwiftStomp 在 MIT 许可下可用。 有关更多信息,请参见 LICENSE 文件。