Web Socket Manager
A Kotlin Multiplatform WebSocket client that manages a single WebSocket connection.
This class provides a high-level API for connecting to a WebSocket server, sending and receiving messages, and managing the lifecycle of the connection in a coroutine-friendly way.
Features:
Connects to a WebSocket server using the specified url.
Supports sending text and binary messages via send.
Receives incoming messages as a SharedFlow of strings (incomingMessages).
Gracefully disconnects using disconnect and flushes pending messages with flush.
Manages coroutines internally with a dedicated CoroutineScope, which can be cancelled via clear.
Notes:
Only one active WebSocket session is maintained per instance.
All operations are asynchronous; sending and receiving messages do not block the caller.
Exceptions during connection or message handling are caught internally; use logging or error handling as needed.
Example usage:
val wsManager = WebSocketManager("wss://example.com/socket")
// Observe incoming messages
wsManager.incomingMessages.onEach { message ->
println("Received: $message")
}.launchIn(CoroutineScope(Dispatchers.Default))
// Connect to the WebSocket server
wsManager.connect()
// Send a text message
wsManager.send("Hello, server!")
// Disconnect and clean up
wsManager.disconnect()
wsManager.clear()