Sling Academy
Home/Kotlin/Kotlin: How to Send and Receive Real-Time Messages via WebSockets

Kotlin: How to Send and Receive Real-Time Messages via WebSockets

Last updated: December 05, 2024

WebSockets are a powerful technology that enables two-way communication between server and clients over a single, long-lived connection. In Kotlin, using WebSockets to send and receive real-time messages can significantly enhance the interactivity of your applications.
In this article, we'll dive into how to handle WebSockets in Kotlin with clear, step-by-step examples and explanations.

What are WebSockets?

WebSockets provide a bidirectional communication channel over a single TCP connection. This allows web applications to handle real-time messages efficiently without the overhead of traditional HTTP requests. After the initial handshake, messages can be sent and received without re-establishing the connection.

Setting Up a Kotlin Project

To get started with WebSockets in Kotlin, you first need to set up a project. We'll use Gradle as the build tool. Let's create a new Kotlin project with WebSocket dependencies.


$ mkdir kotlin-websockets
$ cd kotlin-websockets
$ gradle init --type kotlin-application

Ensure your build.gradle.kts includes the necessary dependencies:


plugins {
    kotlin("jvm") version "1.8.0"
    application
}

group = "com.example"
version = "1.0"
repository {
    mavenCentral()
}

dependencies {
    implementation("org.java-websocket:Java-WebSocket:1.5.2")
    implementation("org.jetbrains.kotlin:kotlin-stdlib")
}

application {
    mainClass.set("com.example.AppKt")
}

Creating a WebSocket Server

Let's create a simple WebSocket server. Java-WebSocket is a reliable library for this purpose. First, implement the server:


import org.java_websocket.server.WebSocketServer
import org.java_websocket.handshake.ClientHandshake
import java.net.InetSocketAddress

class SimpleWebSocketServer(address: InetSocketAddress) : WebSocketServer(address) {
    override fun onOpen(conn: org.java_websocket.WebSocket, handshake: ClientHandshake) {
        println("New connection opened: ${conn.remoteSocketAddress}")
    }

    override fun onClose(conn: org.java_websocket.WebSocket, code: Int, reason: String?, remote: Boolean) {
        println("Connection closed: ${conn.remoteSocketAddress}
reason: $reason")
    }

    override fun onMessage(conn: org.java_websocket.WebSocket, message: String) {
        println("Message received: $message")
    }

    override fun onError(conn: org.java_websocket.WebSocket, ex: Exception) {
        ex.printStackTrace()
    }

    override fun onStart() {
        println("Server started successfully")
    }
}

fun main() {
    val server = SimpleWebSocketServer(InetSocketAddress(8887))
    server.start()
}

This code initializes a simple WebSocket server that listens on port 8887. It handles events such as connection opening, message reception, and connection closing. Now that the server is set up, let's proceed to create a client in Kotlin.

Creating a WebSocket Client

For the client, we also use the Java-WebSocket library, which simplifies connecting to a WebSocket server.


import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI

class SimpleWebSocketClient(serverUri: URI) : WebSocketClient(serverUri) {
    override fun onOpen(handshakeData: ServerHandshake) {
        println("Connected to server")
    }

    override fun onMessage(message: String) {
        println("Message from server: $message")
    }

    override fun onClose(code: Int, reason: String, remote: Boolean) {
        println("Disconnected from server: $reason")
    }

    override fun onError(ex: Exception) {
        ex.printStackTrace()
    }
}

fun main() {
    val client = SimpleWebSocketClient(URI("ws://localhost:8887"))
    client.connect()

    Thread.sleep(1000) // Wait for connection
    if (client.isOpen) {
        client.send("Hello, Server!")
    }
}

This client connects to the server using the specified URI and communicates via WebSockets. It opens a connection to the server, sends a message, and prints out any received messages.

Testing Your WebSocket Setup

First, run your server application, and then execute your client application. Check the console messages on both sides to confirm they can communicate properly. If the setup is successful, you will see messages printed in both your server and client terminal indicating successful message delivery.

Conclusion

With the examples above, you should have a basic understanding of how to implement a WebSocket server and client in Kotlin. WebSockets are ideal for scenarios where you need low-latency, full-duplex communication, such as chat applications or live data feeds. By leveraging Kotlin's features and the Java-WebSocket library, you can build efficient and responsive real-time applications.

Next Article: Using WebSockets for Real-Time Notifications in Kotlin

Previous Article: Setting Up WebSocket Connections with Ktor in Kotlin

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