WebSocketManager

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()

Constructors

Link copied to clipboard
constructor(url: String)

Properties

Link copied to clipboard
val incomingMessages: SharedFlow<String>

Functions

Link copied to clipboard
fun clear()

Cancels all coroutines launched by this WebSocketManager.

Link copied to clipboard
fun connect()

Establishes a WebSocket connection to the server specified by url.

Link copied to clipboard

Closes the current WebSocket connection gracefully.

Link copied to clipboard
fun flush()

Flushes all pending messages in the WebSocket session.

Link copied to clipboard
fun send(message: ByteArray)

Enqueues a final binary frame for sending with the specified content.

fun send(message: String)

Enqueues a text frame for sending with the specified content.