Skip to main content

Introduction to WebSocket in Kotlin Android

Introduction to WebSocket in Kotlin Android

WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It enables real-time, bidirectional communication between clients and servers. In this tutorial, we will explore how to use WebSocket in Kotlin Android.

Prerequisites

To follow along with this tutorial, you will need:

  1. Android Studio installed on your machine.
  2. Basic knowledge of Kotlin and Android development.

Adding WebSocket Support

To use WebSocket in your Kotlin Android project, you need to add the necessary dependencies to your build.gradle file.

  1. Open your project in Android Studio.
  2. Navigate to your app's build.gradle file.
  3. Inside the dependencies block, add the following dependencies:
implementation 'org.java-websocket:Java-WebSocket:1.5.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
  1. Sync your project to download the dependencies.

Establishing a WebSocket Connection

To establish a WebSocket connection, you need to create an instance of the WebSocketClient class.

  1. Create a new Kotlin class called WebSocketClientWrapper.
  2. Inside the WebSocketClientWrapper class, create a class that extends WebSocketClient.
  3. Override the necessary methods:
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI

class MyWebSocketClient(serverUri: URI) : WebSocketClient(serverUri) {
override fun onOpen(handshakedata: ServerHandshake?) {
// Called when the WebSocket connection is successfully established
}

override fun onClose(code: Int, reason: String?, remote: Boolean) {
// Called when the WebSocket connection is closed
}

override fun onError(ex: Exception?) {
// Called when an error occurs in the WebSocket connection
}

override fun onMessage(message: String?) {
// Called when a new message is received from the WebSocket server
}
}
  1. In your MainActivity or any other appropriate activity, create an instance of WebSocketClientWrapper and establish the connection:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.net.URI

class MainActivity : AppCompatActivity() {
private lateinit var webSocketClient: MyWebSocketClient

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

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

override fun onDestroy() {
super.onDestroy()
webSocketClient.close()
}
}

Replace "ws://your-websocket-server-url" with your actual WebSocket server URL.

Sending and Receiving Messages

Once the WebSocket connection is established, you can send and receive messages.

To send a message:

webSocketClient.send("Hello from client!")

To receive a message, implement the onMessage method in your MyWebSocketClient class:

override fun onMessage(message: String?) {
// Handle the received message
}

Closing the WebSocket Connection

To close the WebSocket connection:

webSocketClient.close()

This will trigger the onClose method in your MyWebSocketClient class.

More Examples