CodeBlanks Logo Icon CodeBlanks

WebSocket

Learn realtime communication with Ktor WebSocket.

What is WebSocket?

WebSocket is a bidirectional, persistent connection between client and server. Unlike HTTP, the connection stays open; both sides send data instantly.

In Ktor a WebSocket route is declared with routing { webSocket("/ws") { ... } }. Inside, incoming and outgoing channels exchange data. Example: a chat app, live alerts, game data stream. WebSocket is more efficient than polling HTTP repeatedly; it fits real time applications.

incoming and outgoing

Inside a webSocket block you handle incoming frames from the client with incoming, and send frames to the client with outgoing.

Example: for (frame in incoming) { outgoing.send(Frame.Text("Echo")) }. This loop sends a response as each message arrives. Frame.Text is a text frame; Frame.Binary is for binary data. When the connection closes, incoming ends and the loop exits. This structure merges concurrent data flow with Kotlin coroutines.

Practice Add a WebSocket route

Define fun Application.module(). Inside it open routing { webSocket("/ws") { } }. In main, print println("WebSocket ready").

Starter code

Main.kt
// WebSocket
// write here
import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.server.websocket.*

fun main() {
    
}

Sample solution

Main.kt
fun Application.module() {
    routing {
        webSocket("/ws") {
        }
    }
}

fun main() {
    println("WebSocket ready")
}

Expected output

WebSocket ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the webSocket route

Question
routing {
    ____("/ws") {
        
    }
}
Answer
routing {
    webSocket("/ws") {
        
    }
}

Explanation: The webSocket block opens a route.

2 Which scenario suits WebSocket?

  • Monthly report
  • One time file download
  • Real time chat Correct answer
  • Static page display

Explanation: Chat needs real time data; WebSocket fits.

3 Match WebSocket parts

Term Meaning
webSocket Opens route
incoming Incoming data
outgoing Outgoing data
Frame.Text Text frame

All lessons in Advanced