-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
236: Building a Real-Time Chat App with Ktor WebSockets and Compose
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
connectToChatfunction to accept ausername: String. When the connection is first established, send a special "handshake" message (e.g.,"/join YourName") to the server. - Server Side: Update the
connectionsset to be aMap<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.
There are no comments for now.