CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Ktor client WebSockets plugin for Linux x64 platform - enables full-duplex communication between client and server over TCP connection

Pending
Overview
Eval results
Files

websocket-connections.mddocs/

WebSocket Connections

Core connection establishment functions for creating WebSocket sessions with flexible configuration options, supporting both secure and insecure connections with automatic protocol handling.

Capabilities

WebSocket Connection Function

Opens a WebSocket connection and executes a block with the session, automatically handling connection lifecycle.

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

/**
 * Opens a WebSocket connection with host/port/path parameters
 * @param method HTTP method (default: GET)
 * @param host WebSocket server host
 * @param port WebSocket server port
 * @param path WebSocket endpoint path
 * @param request Additional request configuration
 * @param block Suspend block executed with 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 URL string
 * @param urlString WebSocket URL (ws:// or wss://)
 * @param request Additional request configuration  
 * @param block Suspend block executed with WebSocket session
 */
suspend fun HttpClient.webSocket(
    urlString: String,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

Usage Examples:

// Basic WebSocket connection
client.webSocket("ws://echo.websocket.org") {
    send("Hello WebSocket!")
    
    for (frame in incoming) {
        when (frame) {
            is Frame.Text -> println("Received: ${frame.readText()}")
        }
    }
}

// WebSocket with custom headers
client.webSocket(
    method = HttpMethod.Get,
    host = "localhost", 
    port = 8080,
    path = "/websocket",
    request = {
        header("Authorization", "Bearer $token")
        parameter("room", "general")
    }
) {
    // WebSocket session logic
}

// WebSocket with URL and parameters
client.webSocket("ws://chat.example.com/room/123") {
    // Session handling
}

WebSocket Session Creation

Creates and returns a WebSocket session without automatic closure, allowing manual session management.

/**
 * Opens a WebSocket session and returns it for manual management
 * Session must be manually closed when done
 * @param block Configuration block for HTTP request
 * @return DefaultClientWebSocketSession for manual management
 */
suspend fun HttpClient.webSocketSession(
    block: HttpRequestBuilder.() -> Unit
): DefaultClientWebSocketSession

/**
 * Opens a WebSocket session with host/port/path parameters
 * @param method HTTP method (default: GET)
 * @param host WebSocket server host
 * @param port WebSocket server port  
 * @param path WebSocket endpoint path
 * @param block Additional request configuration
 * @return DefaultClientWebSocketSession for manual management
 */
suspend fun HttpClient.webSocketSession(
    method: HttpMethod = HttpMethod.Get,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    block: HttpRequestBuilder.() -> Unit = {}
): DefaultClientWebSocketSession

/**
 * Opens a WebSocket session using URL string
 * @param urlString WebSocket URL (ws:// or wss://)
 * @param block Additional request configuration
 * @return DefaultClientWebSocketSession for manual management
 */
suspend fun HttpClient.webSocketSession(
    urlString: String,
    block: HttpRequestBuilder.() -> Unit = {}
): DefaultClientWebSocketSession

Usage Examples:

// Manual session management
val session = client.webSocketSession("ws://echo.websocket.org")
try {
    session.send("Hello!")
    val response = session.incoming.receive()
    println("Received: ${(response as Frame.Text).readText()}")
} finally {
    session.close()
}

// Session with custom configuration
val session = client.webSocketSession(
    host = "api.example.com",
    port = 443,
    path = "/websocket/v1"
) {
    header("User-Agent", "MyApp/1.0")
    url.protocol = URLProtocol.WSS
}

WebSocket Shorthand (ws)

Convenient shorthand functions for WebSocket connections, identical to webSocket functions.

/**
 * Shorthand for webSocket function with host/port/path parameters
 * @param method HTTP method (default: GET)
 * @param host WebSocket server host
 * @param port WebSocket server port
 * @param path WebSocket endpoint path  
 * @param request Additional request configuration
 * @param block Suspend block executed with WebSocket session
 */
suspend fun HttpClient.ws(
    method: HttpMethod = HttpMethod.Get,
    host: String? = null,
    port: Int? = null,
    path: String? = null,
    request: HttpRequestBuilder.() -> Unit = {},
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

/**
 * Shorthand for webSocket function with request configuration
 * @param request Configuration block for HTTP request
 * @param block Suspend block executed with WebSocket session
 */
suspend fun HttpClient.ws(
    request: HttpRequestBuilder.() -> Unit,
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

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

Secure WebSocket (wss)

Secure WebSocket connection functions that automatically use WSS protocol.

/**
 * Opens a secure WebSocket (WSS) connection with request configuration
 * Automatically sets protocol to WSS and default port to 443
 * @param request Configuration block for HTTPS request
 * @param block Suspend block executed with WebSocket session
 */
suspend fun HttpClient.wss(
    request: HttpRequestBuilder.() -> Unit,
    block: suspend DefaultClientWebSocketSession.() -> Unit
)

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

/**
 * Opens a secure WebSocket (WSS) connection with host/port/path parameters
 * Automatically sets protocol to WSS
 * @param method HTTP method (default: GET)
 * @param host WebSocket server host
 * @param port WebSocket server port (default: 443 for WSS)
 * @param path WebSocket endpoint path
 * @param request Additional request configuration
 * @param block Suspend block executed with 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 WebSocket with URL
client.wss("wss://secure-echo.websocket.org") {
    send("Secure message")
    for (frame in incoming) {
        when (frame) {
            is Frame.Text -> println("Secure response: ${frame.readText()}")
        }
    }
}

// Secure WebSocket with host/port
client.wss(
    host = "api.example.com",
    path = "/secure-websocket"
) {
    // Session runs over TLS
}

// Secure WebSocket with authentication
client.wss(
    request = {
        url("wss://secure-api.example.com/websocket")
        header("Authorization", "Bearer $accessToken")
    }
) {
    // Authenticated secure session
}

Connection Examples

Basic Echo Server

client.webSocket("ws://echo.websocket.org") {
    // Send message
    send("Hello from Ktor!")
    
    // Receive echo
    val frame = incoming.receive()
    if (frame is Frame.Text) {
        println("Echo: ${frame.readText()}")
    }
}

Chat Application

client.webSocket(
    host = "chat.example.com",
    path = "/chat"
) {
    // Join chat room
    send("JOIN:general")
    
    // Send and receive messages
    launch {
        while (true) {
            val message = readLine() ?: break
            send("MESSAGE:$message")
        }
    }
    
    for (frame in incoming) {
        when (frame) {
            is Frame.Text -> {
                val message = frame.readText()
                println("Chat: $message")
            }
            is Frame.Close -> break
        }
    }
}

Secure Trading WebSocket

client.wss(
    host = "api.exchange.com",
    path = "/ws/v1/stream"
) {
    // Subscribe to price feeds
    send("""{"action":"subscribe","symbols":["BTCUSD","ETHUSD"]}""")
    
    for (frame in incoming) {
        when (frame) {
            is Frame.Text -> {
                val data = json.decodeFromString<PriceUpdate>(frame.readText())
                handlePriceUpdate(data)
            }
        }
    }
}

Custom Headers and Parameters

client.webSocket(
    urlString = "wss://api.example.com/websocket",
    request = {
        header("User-Agent", "MyApp/1.0.0")
        header("Authorization", "ApiKey $apiKey")
        parameter("version", "v2")
        parameter("format", "json")
    }
) {
    // WebSocket session with custom headers
}

Install with Tessl CLI

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

docs

frame-operations.md

index.md

plugin-configuration.md

serialization-support.md

session-management.md

websocket-connections.md

tile.json