Sling Academy
Home/Kotlin/Building a Simple Chat App with WebSockets in Kotlin

Building a Simple Chat App with WebSockets in Kotlin

Last updated: November 30, 2024

In this tutorial, we will build a basic chat application using WebSockets in Kotlin. WebSockets allow us to open an interactive communication session between a user's browser and a server. We will use Kotlin for the server part and JavaScript for the client. Let's dive in!

Setting Up the Server

First, we need to set up a basic server using Kotlin. To get started, create a new Kotlin project and include the necessary dependencies for WebSockets. We'll use Ktor, a Kotlin framework for building asynchronous servers.

dependencies {
    implementation 'io.ktor:ktor-server-netty:2.7.0'
    implementation 'io.ktor:ktor-websockets:2.7.0'
}

Creating the WebSocket Endpoint

Next, we create an endpoint to handle WebSocket connections. In Ktor, we can easily set up a WebSocket route and define the behavior for incoming connections.

import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.application.*
import io.ktor.server.routing.routing
import io.ktor.server.websocket.*
import io.ktor.websocket.*
import kotlinx.coroutines.channels.consumeEach

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(WebSockets)
        routing {
            webSocket("/chat") { // this handles requests to ws://localhost:8080/chat
                send("You are connected!")
                incoming.consumeEach { frame ->
                    if (frame is Frame.Text) {
                        val incomingMessage = frame.readText()
                        send("Server received: $incomingMessage")
                    }
                }
            }
        }
    }.start(wait = true)
}

Setting Up the Client

Now, let's create a simple HTML client to interact with our WebSocket server. We'll use plain JavaScript to keep things simple.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kotlin WebSocket Chat</title>
</head>
<body>

<h1>WebSocket Chat App</h1>
<input id="messageInput" type="text" placeholder="Type a message..."/>
<button onclick="sendMessage()">Send</button>
<div id="chatLog"></div>

<script>
    const socket = new WebSocket('ws://localhost:8080/chat');

    socket.onmessage = function(event) {
        const chatLog = document.getElementById('chatLog');
        chatLog.innerHTML += '<p>' + event.data + '</p>';
    };

    function sendMessage() {
        const input = document.getElementById('messageInput');
        socket.send(input.value);
        input.value = '';
    }
</script>

</body>
</html>

With the server and client set up, you can now test your chat application. Run your server and open the HTML file in a web browser. You should be able to enter messages in the input field and see server responses in real-time!

Conclusion

You've built a simple chat application using WebSockets with Kotlin and Ktor for the server-side and JavaScript for the client-side. This setup allows real-time messaging, which is fundamental for modern applications involving chat or collaborative functionality. Experiment further by adding user identifiers, handling binary data, or more sophisticated message broker techniques.

Next Article: How to Use Kotlin Coroutines with WebSockets

Previous Article: Kotlin: How to Parse WebSocket Messages (JSON and Text)

Series: Networking in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin