Pie.host

PieSocket SDK For Kotlin Multiplatform

Pie.host offers the PieSocket Kotlin Multiplatform SDK for Android, iOS and JVM (desktop and server) projects. One shared Kotlin codebase gets pub/sub channels, presence, private channels, binary messages and automatic reconnect.

Installation

Add the SDK to your shared module.

// build.gradle.kts
kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("com.piehost:piesocket-kmp:8.0.0")
        }
    }
}

Android apps need compileSdk = 37 or newer (required by the OkHttp version Ktor uses). The minimum supported minSdk is 24.

Usage

Initialize PieSocket

Pass your API key and Cluster ID to the PieSocket class.

Get your API key and Cluster ID here: Create PieSocket account

val pie = PieSocket(
    PieSocketOptions(
        apiKey = "your-api-key",
        clusterId = "your-cluster-id"
    )
)

Subscribe to a channel

subscribe is a suspend function, call it from a coroutine.

val chat = pie.subscribe("chat-room")

With protocol version 4 (the default), every channel you subscribe to shares one WebSocket connection. Set version = 3 in PieSocketOptions to open one connection per channel.

Listen for events

chat.listen("message") { e ->
    println(e.string("text"))
}

Publish an event

chat.publish("message", mapOf("text" to "hello"))

By default you don't receive your own messages, set notifySelf = true to get them too.

Unsubscribe and close

pie.unsubscribe("chat-room")
pie.close()

Receiving messages

channel.listen("event") { e -> }          // one callback per event, replaces the previous one
val h = channel.addListener("event") { }  // any number of callbacks, h.remove() to stop
channel.listen("*") { e -> e.event }      // every event
channel.events.collect { e -> }           // as a Flow
channel.on("close") { }                   // lifecycle: open, close, error, message

Each PieEvent has event, data (JsonElement), meta, bytes (for binary messages) and a string("key") helper.

Callbacks run on a background thread. To get them on the main thread, for example to update UI on Android, pass callbackContext = Dispatchers.Main in PieSocketOptions.

Sending messages

// Data and meta accept maps, lists or JsonElement
channel.publish("event", mapOf("a" to 1), meta = mapOf("from" to "me"))

// Binary, other clients receive it as the system::binary event
channel.send(byteArray)

// Direct message to one user
channel.send(buildJsonObject {
    put("event", "dm")
    put("system::to", "bob")
})

See: Binary data streaming and Send private messages

Presence

Enable presence and set a user ID to see who is in a channel.

val pie = PieSocket(
    PieSocketOptions(apiKey = key, presence = true, userId = "alice")
)
val room = pie.subscribe("room")

room.members           // List<Member> (uuid, user)
room.membersFlow       // StateFlow of members
room.refreshMembers()  // re-sync from the server

Channels named presence-* always have presence enabled. Each connection (tab, device) counts as its own member.

See: List online members

Private channels

Channels starting with private- need a JWT signed for that channel. The SDK uses the first of these that is set:

// 1. A token for one channel
pie.subscribe("private-orders", jwt = ordersToken)

// 2. One token for the connection (fits a single channel)
PieSocketOptions(apiKey = key, jwt = token)

// 3. An auth endpoint, called with channel_name, returns {"auth": "<jwt>"}
PieSocketOptions(apiKey = key, authEndpoint = "https://example.com/auth")

Use authHeaders to send headers (for example a session token) to your auth endpoint.

See: Authenticate connections

Reconnect

When the connection drops, the client reconnects with exponential backoff (1 second base, 30 second cap, with jitter) and subscribes to every channel again. It stops on fatal server errors such as an invalid token or unknown API key.

Set autoReconnect = false to turn this off. If the first connection fails, subscribe throws a PieSocketException.

Configuration options

Option Default
apiKey required
clusterId demo
clusterDomain <clusterId>.piesocket.com, set it for self-hosted servers, e.g. localhost:4001
ssl true
version 4
notifySelf false
presence false
jwt, authEndpoint, authHeaders, forceAuth private channels
userId null
autoReconnect true
consoleLogs false
callbackContext background thread

See: PieSocket configuration

Using it from Swift

When the shared module is used from Swift, subscribe is async and callbacks are closures. Swift-only apps should use the iOS SDK instead.