This is a package that contains a client behaving as an async wrapper for the URLSessionWebSocketTask provided by Apple.
letclient=AsyncWebSocketClient(url:URL(string:"ws://localhost:8765/")!)tryawait client.connect()tryawait client.send(.string("Hello world!")) // Either raw data or strings can be sent
letstream=await client.listenStream() // Returns an AsyncStream of events
forawaiteventin stream {print(event) // Print events such as data received, connection opened, connection closed
}You can also send encodable objects to the client:
structMyEncodableObject:Encodable,Sendable{lettitle:String}letobjectToEncode=MyEncodableObject(title:"Title")tryawait 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