A modern, easy-to-use WebSocket client for Swift, powered by Combine and async/await.
- Modern Concurrency: Built with
async/awaitand exposes streams via CombinePublisher. - Protocol-Oriented: Easy to test and extend.
- Fluent Builder API: Intuitive and chainable configuration.
- Extensible with Decorators: Add custom functionalities like auto-reconnection with ease.
- Dual Backend Support: Choose between
URLSessionandNetwork.framework.
- iOS 15.0+ / macOS 12.0+ / watchOS 8.0+ / tvOS 15.0+
- Swift 5.9+
You can add SwiftWebSocketClient to your project by adding it as a package dependency.
- In Xcode, open your project and navigate to File > Add Packages...
- Paste the repository URL:
https://github.com/TaeJoongYoon/SwiftWebSocketClient.git - Follow the prompts to add the package to your target.
Here's a basic example of how to connect and listen for messages:
import SwiftWebSocketClient
import Combine
let url = URL(string: "wss://yourwebsocketserver.com")!
let client = WebSocketBuilder(url: url).build(implementation: .urlSession)
var cancellables = Set<AnyCancellable>()
// Subscribe to status updates
client.status
.sink { status in
print("Connection Status: \(status)")
// When connected, send a message.
if case .connected = status {
Task {
print("Sending 'Hello' to the server.")
try? await client.send(message: .string("Hello from Swift!"))
}
}
}
.store(in: &cancellables)
// Subscribe to incoming messages
client.message
.sink { message in
switch message {
case .string(let text):
print("Received message: \(text)")
case .data(let data):
print("Received data: \(data.count) bytes")
}
}
.store(in: &cancellables)
// Connect to the server
client.connect(autoListen: true)This project is licensed under the MIT License - see the LICENSE file for details.