LCL WebSocket

LCL WebSocket 是一个跨平台的 WebSocket [RFC 6455] 库,使用 Swift 编写并专为 Swift 设计,构建于 SwiftNIO 之上。

特性

要求

入门指南

Swift Package Manager

将以下内容添加到您的 Package.swift

dependencies: [
    .package(url: "https://github.com/Local-Connectivity-Lab/lcl-websocket.git", from: "1.0.0")
]

基本用法

客户端

let config = LCLWebSocket.Configuration(
    maxFrameSize: 1 << 16,
    autoPingConfiguration: .enabled(pingInterval: .seconds(4), pingTimeout: .seconds(10)),
    leftoverBytesStrategy: .forwardBytes
)

// Initialize the client
var client = LCLWebSocket.client()
client.onOpen { websocket in
    websocket.send(.init(string: "hello"), opcode: .text, promise: nil)
}

client.onBinary { websocket, binary in
    print("received binary: \(binary)")
}

client.onText { websocket, text in
    print("received text: \(text)")
}

try client.connect(to: "ws://127.0.0.1:8080", configuration: config).wait()

服务器

let config = LCLWebSocket.Configuration(
    maxFrameSize: 1 << 16,
    autoPingConfiguration: .disabled,
    leftoverBytesStrategy: .forwardBytes
)

server.onPing { websocket, buffer in
    print("onPing: \(buffer)")
    websocket.pong(data: buffer)
}
server.onPong { ws, buffer in
    print("onPong: \(buffer)")
}
server.onBinary { websocket, buffer in
    websocket.send(buffer, opcode: .binary, promise: nil)
}
server.onText { websocket, text in
    print("received text: \(text)")
    websocket.send(.init(string: text), opcode: .text, promise: nil)
}
server.onClosing { code, reason in
    print("on closing: \(String(describing: code)), \(String(describing: reason))")
}

// wait forever
try server.listen(host: "127.0.0.1", port: 8080, configuration: config).wait()

待办事项

贡献

欢迎任何贡献和 pull request! 但是,在您计划实现某些功能或尝试修复不确定的问题之前,建议首先发起讨论。 您也可以加入我们的 Discord 频道,或者访问我们的 网站

许可证

LCLPing 基于 Apache License 发布。 有关更多详细信息,请参见 LICENSE