This is a package that contains a client behaving as a wrapper for the URLSessionWebSocketTask provided by Apple.
let client = AsyncWebSocketClient(url: URL(string: "ws://localhost:8765/")!)
try await client.connect()
try await client.send(.string("Hello world!")) // Either raw data or strings can be sent
let stream = await client.listenStream() // Returns an AsyncStream of events
for await event in stream {
print(event) // Print events such as data received, connection opened, connection closed
}
You can also send encodable objects to the client:
struct MyEncodableClass: Encodable {
let title: String
}
let objectToEncode = MyEncodableClass(title: "Title")
try await client.sendJSONData(objectToEncode)
AsyncWebSocketClient conforms to AsyncWebSocketClientProtocol and it is recommended to use dependency injection to make testing easier. For convenience, this library also includes a mock target AsyncWebSocketClientMocks
which you can use if you just need a simple mock. You could optionally add your own mock class conforming to AsyncWebSocketClientProtocol.
In Xcode, select File --> Swift Packages --> Add Package Dependency and then add the following url:
https://github.com/Henryforce/AsyncWebSocketClient