Skip to content

A simple client behaving as a wrapper for the URLSessionWebSocketTask class

License

Notifications You must be signed in to change notification settings

Henryforce/AsyncWebSocketClient

Repository files navigation

AsyncWebSocketClient

badge-platforms badge-spm

This is a package that contains a client behaving as a wrapper for the URLSessionWebSocketTask provided by Apple.

Usage

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
}

Advanced usage

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)

How to test

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.

Installation

Swift Package Manager

In Xcode, select File --> Swift Packages --> Add Package Dependency and then add the following url:

https://github.com/Henryforce/AsyncWebSocketClient

About

A simple client behaving as a wrapper for the URLSessionWebSocketTask class

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published