Skip to main content

How to establish a WebSocket connection in Kotlin Android

How to establish a WebSocket connection in Kotlin Android.

Here's a step-by-step tutorial on how to establish a WebSocket connection in Kotlin Android.

Step 1: Add the necessary dependencies

To begin, open your project's build.gradle file and add the following dependencies:

implementation 'org.java-websocket:Java-WebSocket:1.5.1'

Step 2: Create a WebSocket client

Create a new Kotlin class for your WebSocket client. You can name it whatever you like, for example, WebSocketClient.kt. In this class, import the necessary classes:

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

Next, create a class that extends WebSocketClient:

class MyWebSocketClient(serverUri: URI) : WebSocketClient(serverUri) {
override fun onOpen(handshakedata: ServerHandshake?) {
// Called when the WebSocket connection is established
// You can perform any initialization tasks here
}

override fun onClose(code: Int, reason: String?, remote: Boolean) {
// Called when the WebSocket connection is closed
// You can perform any cleanup tasks here
}

override fun onMessage(message: String?) {
// Called when a new message is received from the WebSocket server
// Handle the received message here
}

override fun onError(ex: Exception?) {
// Called when an error occurs
// Handle the error here
}
}

Step 3: Connect to the WebSocket server

In your activity or fragment where you want to establish the WebSocket connection, create an instance of your MyWebSocketClient class and connect to the WebSocket server:

val serverUri = URI("ws://your-websocket-server-url")
val webSocketClient = MyWebSocketClient(serverUri)
webSocketClient.connect()

Make sure to replace "your-websocket-server-url" with the actual URL of your WebSocket server.

Step 4: Send and receive messages

To send a message to the WebSocket server, use the send method of your MyWebSocketClient instance:

webSocketClient.send("Hello, WebSocket server!")

To handle received messages, implement the logic inside the onMessage method of your MyWebSocketClient class. For example:

override fun onMessage(message: String?) {
// Handle the received message here
runOnUiThread {
// Update UI or perform other tasks based on the received message
}
}

Step 5: Close the WebSocket connection

To close the WebSocket connection, call the close method of your MyWebSocketClient instance:

webSocketClient.close()

That's it! You have successfully established a WebSocket connection in Kotlin Android. You can now send and receive messages with the WebSocket server.

Remember to handle any exceptions that may occur during the WebSocket connection, and also make sure to disconnect the WebSocket client when it's no longer needed to avoid resource leaks.