CtrlK
BlogDocsLog inGet started
Tessl Logo

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

WebSocket plugin for Ktor HTTP client enabling full-duplex real-time communication

Pending
Overview
Eval results
Files

connection-management.mddocs/

Connection Management

Functions for establishing and managing WebSocket connections with support for various URL formats, request configurations, and connection lifecycle management.

Capabilities

WebSocket Connection Functions

Establish WebSocket connections using different URL and configuration patterns.

/**
 * Opens a block with DefaultClientWebSocketSession using request builder
 */
suspend fun HttpClient.webSocket(
    request: HttpRequestBuilder.() -> Unit,
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Opens a block with DefaultClientWebSocketSession using URL components
 */
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 block with DefaultClientWebSocketSession using URL string
 */
suspend fun HttpClient.webSocket(
    urlString: String,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

Usage Examples:

import io.ktor.client.*
import io.ktor.client.plugins.websocket.*
import io.ktor.websocket.*

val client = HttpClient {
    install(WebSockets)
}

// Using request builder
client.webSocket({
    url("ws://localhost:8080/websocket")
    parameter("token", "abc123")
}) {
    send("Hello WebSocket!")
    
    for (frame in incoming) {
        when (frame) {
            is Frame.Text -> println("Received: ${frame.readText()}")
            is Frame.Close -> break
            else -> {}
        }
    }
}

// Using URL components
client.webSocket(
    method = HttpMethod.Get,
    host = "localhost",
    port = 8080,
    path = "/chat"
) {
    send("Connected to chat")
    // Handle messages...
}

// Using URL string
client.webSocket("ws://example.com/stream") {
    // WebSocket logic here
}

WebSocket Session Functions

Create persistent WebSocket sessions that can be managed independently.

/**
 * Opens a DefaultClientWebSocketSession using request builder
 */
suspend fun HttpClient.webSocketSession(
    block: HttpRequestBuilder.() -> Unit
): DefaultClientWebSocketSession

/**
 * Opens a DefaultClientWebSocketSession using URL components  
 */
suspend fun HttpClient.webSocketSession(
    method: HttpMethod = HttpMethod.Get,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    block: HttpRequestBuilder.() -> Unit = {}
): DefaultClientWebSocketSession

/**
 * Opens a DefaultClientWebSocketSession using URL string
 */
suspend fun HttpClient.webSocketSession(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): DefaultClientWebSocketSession

Usage Examples:

// Create and manage session manually
val session = client.webSocketSession("ws://localhost:8080/websocket")

try {
    session.send("Hello!")
    
    val response = session.incoming.receive()
    if (response is Frame.Text) {
        println("Server replied: ${response.readText()}")
    }
} finally {
    session.close()
}

// Session with custom headers
val authenticatedSession = client.webSocketSession {
    url("ws://api.example.com/websocket")
    header("Authorization", "Bearer $token")
}

Short Alias Functions (ws)

Convenient aliases for WebSocket connection functions.

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

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

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

Usage Examples:

// Short aliases for convenience
client.ws("ws://localhost:8080/ws") {
    send("Quick connection")
}

client.ws(host = "localhost", port = 8080, path = "/api/ws") {
    // WebSocket operations
}

Secure WebSocket Functions (wss)

Establish secure WebSocket connections over TLS/SSL.

/**
 * Opens a block with secure DefaultClientWebSocketSession using request builder
 */
suspend fun HttpClient.wss(
    request: HttpRequestBuilder.() -> Unit,
    block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit

/**
 * Opens a block with secure DefaultClientWebSocketSession using URL string
 */
suspend fun HttpClient.wss(
    urlString: String,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit

/**
 * Opens a block with secure DefaultClientWebSocketSession using URL components
 */
suspend fun HttpClient.wss(
    method: HttpMethod = HttpMethod.Get,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
): Unit

Usage Examples:

// Secure WebSocket connection
client.wss("wss://secure.example.com/websocket") {
    send("Secure connection established")
    
    for (frame in incoming) {
        when (frame) {
            is Frame.Text -> {
                val message = frame.readText()
                println("Secure message: $message")
            }
            is Frame.Close -> break
            else -> {}
        }
    }
}

// Secure connection with authentication
client.wss(
    host = "api.example.com",
    port = 443,
    path = "/secure-ws"
) {
    header("Authorization", "Bearer $secureToken")
} {
    // Handle secure WebSocket communication
}

URL Protocol Configuration

Automatic protocol handling for WebSocket connections.

Protocol Mapping:

  • ws:// - Standard WebSocket protocol (default port 80)
  • wss:// - Secure WebSocket protocol over TLS (default port 443)
  • Automatic protocol upgrade from HTTP to WebSocket during connection handshake

Usage Examples:

// Protocol is automatically set based on function used
client.webSocket("ws://example.com/ws") { /* insecure */ }
client.wss("wss://example.com/ws") { /* secure */ }

// Manual protocol specification
client.webSocket {
    url {
        protocol = URLProtocol.WS  // or URLProtocol.WSS
        host = "example.com"
        port = protocol.defaultPort
        path("/websocket")
    }
} {
    // WebSocket operations
}

Connection Lifecycle

WebSocket connections automatically handle the HTTP upgrade handshake and manage the connection lifecycle.

Connection Process:

  1. HTTP request sent with WebSocket upgrade headers
  2. Server responds with 101 Switching Protocols
  3. Connection upgraded to WebSocket protocol
  4. Session block executed with active WebSocket
  5. Connection automatically closed when block completes

Error Handling:

try {
    client.webSocket("ws://unreliable.example.com/ws") {
        send("Test message")
        // Connection operations
    }
} catch (e: WebSocketException) {
    println("WebSocket error: ${e.message}")
} catch (e: Exception) {
    println("Connection error: ${e.message}")
}

Install with Tessl CLI

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

docs

connection-management.md

index.md

message-handling.md

plugin-configuration.md

tile.json