WebSocket plugin for Ktor HTTP client enabling full-duplex real-time communication
—
Functions for establishing and managing WebSocket connections with support for various URL formats, request configurations, and connection lifecycle management.
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
}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 = {}
): DefaultClientWebSocketSessionUsage 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")
}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
): UnitUsage 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
}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
): UnitUsage 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
}Automatic protocol handling for WebSocket connections.
Protocol Mapping:
ws:// - Standard WebSocket protocol (default port 80)wss:// - Secure WebSocket protocol over TLS (default port 443)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
}WebSocket connections automatically handle the HTTP upgrade handshake and manage the connection lifecycle.
Connection Process:
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