Skip to Content
Course content

236: Building a Real-Time Chat App with Ktor WebSockets and Compose

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of a standard HTTP request like sending a letter through the mail. You send a request, you wait, and eventually, you get a response back. Once that's done, the transaction is over. If you want to know if there's new information, you have to send another letter. That's fine for a blog post, but it's a nightmare for a chat app.

WebSockets, on the other hand, are like a phone call. Once the connection is established, the line stays open. Either person can talk whenever they want, and the other person hears it instantly without having to ask, "Do you have any updates for me?"

In our Ktor and Compose setup, the "phone call" is the WebSocket session. The server doesn't just respond to a request and hang up; it keeps a list of active "callers" (sessions) and broadcasts messages to everyone on the line the moment a new one arrives.

Opening the Line with Ktor

To get this working, we first need to tell our Ktor server that it's allowed to handle these persistent connections. I usually see people forget the install(WebSockets) block, which results in a confusing 404 or a connection rejection. Once that's in place, we define a specific route for our chat.

install(WebSockets)

routing {
    webSocket("/chat") {
        // This block is our "active call." 
        // Everything inside here happens while the client is connected.
        try {
            for (frame in incoming) {
                if (frame is Frame.Text) {
                    val text = frame.readText()
                    // We'll broadcast this to others in a moment
                    send("Server received: $text") 
                }
            }
        } catch (e: Exception) {
            println("Connection closed: ${e.localizedMessage}")
        }
    }
}

The incoming channel is where the magic happens. It's a stream of frames. I prefer using a for loop here because it naturally suspends the coroutine until a new message arrives, keeping the thread free for other users.

Managing the Global Conversation

A chat app isn't much use if you're just talking to the server. We need a way to track everyone who is currently connected. A simple ConcurrentHashMap or a Set of sessions works well here. When one person sends a message, the server iterates through that set and pushes the message out to everyone else.

val connections = Collections.synchronizedSet(mutableSetOf<DefaultWebSocketServerSession>())

routing {
    webSocket("/chat") {
        connections.add(this)
        try {
            for (frame in incoming) {
                if (frame is Frame.Text) {
                    val message = frame.readText()
                    // Broadcast to every connected client
                    connections.forEach { session ->
                        session.send(Frame.Text("User: $message"))
                    }
                }
            }
        } finally {
            connections.remove(this)
        }
    }
}

Notice the finally block. In the real world, users lose signal or kill the app. If you don't remove the session from your set, you'll end up trying to send messages to "ghost" connections, which will eventually tank your server's performance.

Wiring the Stream into Compose

On the frontend, the challenge is mapping a continuous stream of data into something Compose can render. You don't want to trigger a full recomposition of your entire screen every time a single character arrives. The best approach is to pipe the WebSocket messages into a MutableStateFlow within a ViewModel.

class ChatViewModel : ViewModel() {
    private val _messages = MutableStateFlow<List<String>> شاهد(emptyList())
    val messages: StateFlow<List<String>> = _messages

    fun connectToChat() {
        viewModelScope.launch {
            val client = HttpClient { install(WebSockets) }
            client.webSocket(host = "10.0.2.2", port = 8080, path = "/chat") {
                for (frame in incoming) {
                    if (frame is Frame.Text) {
                        val text = frame.readText()
                        _messages.update { it + text }
                    }
                }
            }
        }
    }
}

In your Composable, you just use collectAsState() on that flow. Now, as the server pushes a new Frame.Text, the state updates, and Compose surgically updates only the LazyColumn displaying the messages. It's incredibly efficient because the UI is simply reacting to the stream of data coming off the "phone line."




📋 Practical Task

Implementing a User-Identified Message System for DevChat

Right now, the chat app is anonymous—everyone is just "User." Your task is to modify both the server and the client to support identity.

  • Client Side: Modify the connectToChat function to accept a username: String. When the connection is first established, send a special "handshake" message (e.g., "/join YourName") to the server.
  • Server Side: Update the connections set to be a Map<DefaultWebSocketServerSession, String>. When you receive a message starting with "/join ", store that username associated with that session.
  • Broadcasting: Modify the broadcast loop so that instead of saying "User: message", it looks up the session's username in the map and sends "Username: message".

Verify your work by running two different emulator instances (or an emulator and a physical device) and ensuring you can see who sent which message in real-time.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.