WebSocketKit

Swift 5.0 SPM CI

WebSocketKit 是围绕 `Network` 框架构建的一个小型封装,用于处理 WebSocket 连接。

安装

Swift 包管理器

要使用 Apple 的 Swift 包管理器 进行集成,请将以下内容作为依赖项添加到您的 Package.swift 文件中:

dependencies: [
    .package(url: "https://github.com/alexanderwe/WebSocketKit.git", from: "1.0.0")
]

或者,导航到您的 Xcode 项目,选择 Swift Packages 并单击 + 图标以搜索 WebSocketKit

手动

如果您不想使用上述任何依赖项管理器,您可以手动将 WebSocketKit 集成到您的项目中。只需将 Sources 文件夹拖到您的 Xcode 项目中即可。

用法

首先导入 WebSocketKit

import WebSocketKit

定义一个 WebSocket 实例

let websocket = WebsSocket(url: URL(string: "wss://echo.websocket.org")!)

创建一个符合 WebSocketConnectionDelegate 协议的类的实例也是有意义的,以便接收 WebSocket 事件。 请注意,您还需要导入 Network 框架才能访问 NWProtocolWebSocket

import Network


class WebSocketDelegate: WebSocketConnectionDelegate {

    func webSocketDidConnect(connection: WebSocketConnection) {
        print("WebSocket did connect")
    }

    func websocketDidPrepare(connection: WebSocketConnection) {
        print("WebSocket did prepare")
    }

    func webSocketDidDisconnect(connection: WebSocketConnection, closeCode: NWProtocolWebSocket.CloseCode, reason: Data?) {
        print("WebSocket did disconnect")
    }

    func websocketDidCancel(connection: WebSocketConnection) {
        print("WebSocket did cancel")
    }

    func webSocketDidReceiveError(connection: WebSocketConnection, error: Error) {
        print("WebSocket did receive error: \(error)")
    }

    func webSocketDidReceivePong(connection: WebSocketConnection) {
        print("WebSocket did receive pong")
    }

    func webSocketDidReceiveMessage(connection: WebSocketConnection, string: String) {
        print("WebSocket did receive string message: \(string)")
    }

    func webSocketDidReceiveMessage(connection: WebSocketConnection, data: Data) {
        print("WebSocket did receive data message")
    }
}

将 delegate 实例设置为 WebSocket 实例,然后开始侦听事件

let delegate = WebSocketDelegate()
websocket.delegate = delegate

websocket.connect() // Connects to the url specified in the initializer and listens for messages

自定义标头

通常需要将自定义标头附加到连接。 您可以通过在 WebSocket 类的初始化程序中指定它们来实现。

let websocket = Websocket(url: URL(string: "wss://echo.websocket.org")!,
                          additionalHeaders: [
                            "Authorization:": "Bearer <someToken>",
                            "My-Custom-Header-Key:": "My-Custom-Header-Value"
                          ]
)

贡献

非常欢迎贡献 🙌