CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-client-websockets-iosx64

Ktor client WebSocket plugin for iOS x64 target providing WebSocket client capabilities for iOS simulator applications using Kotlin Multiplatform.

Pending
Overview
Eval results
Files

websocket-connections.mddocs/

WebSocket Connections

Connection establishment functions providing flexible ways to connect to WebSocket servers with both high-level and low-level APIs.

Capabilities

WebSocket Connection Functions

High-level functions that execute a block with an active WebSocket session and automatically handle connection cleanup.

/**
 * Opens a WebSocket connection and executes a block with the session
 * @param request Configuration block for the HTTP request
 * @param block Suspend block executed with the WebSocket session
 */
suspend fun HttpClient.webSocket(
    request: HttpRequestBuilder.() -> Unit,
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Opens a WebSocket connection using method, host, port, and path parameters
 * @param method HTTP method for the WebSocket handshake (default: GET)
 * @param host Target hostname
 * @param port Target port number
 * @param path Target path
 * @param request Additional request configuration
 * @param block Suspend block executed with the WebSocket session
 */
suspend fun HttpClient.webSocket(
    method: HttpMethod = HttpMethod.Get,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Opens a WebSocket connection using a URL string
 * @param urlString WebSocket URL (ws:// or wss://)
 * @param request Additional request configuration
 * @param block Suspend block executed with the WebSocket session
 */
suspend fun HttpClient.webSocket(
    urlString: String,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

Usage Examples:

// Connect using request builder
client.webSocket({
    url("ws://echo.websocket.org")
    header("Authorization", "Bearer token")
}) {
    send("Hello!")
    val response = incoming.receive()
    // Handle response...
}

// Connect using parameters
client.webSocket(
    method = HttpMethod.Get,
    host = "echo.websocket.org",
    port = 80,
    path = "/websocket"
) {
    send("Hello!")
    // Handle messages...
}

// Connect using URL string
client.webSocket("ws://echo.websocket.org") {
    send("Hello!")
    // Handle messages...
}

WebSocket Alias Functions

Shorter alias functions for WebSocket connections.

/**
 * Alias for webSocket function using method, host, port, and path
 */
suspend fun HttpClient.ws(
    method: HttpMethod = HttpMethod.Get,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Alias for webSocket function using request builder
 */
suspend fun HttpClient.ws(
    request: HttpRequestBuilder.() -> Unit,
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Alias for webSocket function using URL string
 */
suspend fun HttpClient.ws(
    urlString: String,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

Secure WebSocket Functions

Functions for establishing secure WebSocket connections (WSS).

/**
 * Opens a secure WebSocket connection using request builder
 * @param request Configuration block for the HTTPS request
 * @param block Suspend block executed with the WebSocket session
 */
suspend fun HttpClient.wss(
    request: HttpRequestBuilder.() -> Unit,
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Opens a secure WebSocket connection using URL string
 * @param urlString Secure WebSocket URL (wss://)
 * @param request Additional request configuration
 * @param block Suspend block executed with the WebSocket session
 */
suspend fun HttpClient.wss(
    urlString: String,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Opens a secure WebSocket connection using method, host, port, and path
 * @param method HTTP method for the WebSocket handshake (default: GET)
 * @param host Target hostname
 * @param port Target port number (defaults to 443 for WSS)
 * @param path Target path
 * @param request Additional request configuration
 * @param block Suspend block executed with the WebSocket session
 */
suspend fun HttpClient.wss(
    method: HttpMethod = HttpMethod.Get,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

Usage Examples:

// Secure connection using URL
client.wss("wss://secure.websocket.org") {
    send("Secure message")
    // Handle secure communication...
}

// Secure connection with custom headers
client.wss("wss://api.example.com/ws") {
    header("Authorization", "Bearer ${getToken()}")
    header("User-Agent", "MyApp/1.0")
} {
    // WebSocket session handling...
}

// Secure connection using parameters
client.wss(
    host = "secure.websocket.org",
    port = 443,
    path = "/secure-ws"
) {
    send("Hello secure server!")
    // Handle responses...
}

Connection Lifecycle

Automatic Cleanup

All connection functions (webSocket, ws, wss) automatically handle connection cleanup:

client.webSocket("ws://example.com") {
    // Connection is established here
    send("Hello!")
    
    // Process messages
    for (frame in incoming) {
        // Handle frame...
    }
    
    // Connection is automatically closed when block exits
    // Even if an exception occurs
}

Connection State

Within the connection block, you have access to the full WebSocket session:

client.webSocket("ws://example.com") {
    // Session properties
    println("Connection established with ${call.request.url}")
    
    // Send messages
    send("Text message")
    send(byteArrayOf(1, 2, 3, 4))
    
    // Receive messages
    for (frame in incoming) {
        when (frame) {
            is Frame.Text -> println("Text: ${frame.readText()}")
            is Frame.Binary -> println("Binary: ${frame.data.size} bytes")
            is Frame.Close -> {
                println("Connection closed: ${frame.readReason()}")
                break
            }
            else -> {}
        }
    }
}

Error Handling

Connection functions throw WebSocketException for handshake failures or connection issues:

try {
    client.webSocket("ws://invalid-server.com") {
        // This block won't execute if handshake fails
    }
} catch (e: WebSocketException) {
    println("WebSocket connection failed: ${e.message}")
} catch (e: Exception) {
    println("Other error: ${e.message}")
}

Protocol Handling

URL Protocol Conversion

The connection functions automatically handle protocol conversion:

  • webSocket and ws functions convert HTTP URLs to WebSocket URLs (http:// → ws://, https:// → wss://)
  • wss functions enforce secure WebSocket protocol (wss://)
  • Default ports are handled automatically (80 for ws://, 443 for wss://)

Request Customization

All connection functions accept request customization blocks:

client.webSocket("ws://example.com") {
    // Customize the WebSocket handshake request
    header("Authorization", "Bearer token")
    header("Sec-WebSocket-Protocol", "chat, superchat")
    parameter("room", "general")
    userAgent("MyWebSocketClient/1.0")
} {
    // WebSocket session handling...
}

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-client-websockets-iosx64

docs

index.md

message-serialization.md

plugin-configuration.md

session-management.md

websocket-connections.md

tile.json