Skip to main content

How to handle multiple WebSocket connections in Kotlin Android

How to handle multiple WebSocket connections in Kotlin Android.

Here's a detailed step-by-step tutorial on how to handle multiple WebSocket connections in Kotlin Android.

Step 1: Set up the project

Start by creating a new Android project in your preferred IDE. Make sure you have the necessary dependencies for networking and WebSocket communication. For this tutorial, we'll be using the kotlinx.coroutines library for handling asynchronous tasks.

Step 2: Create a WebSocketManager class

Create a new Kotlin class called WebSocketManager. This class will be responsible for managing multiple WebSocket connections. Inside the class, initialize a HashMap to store the WebSocket instances.

class WebSocketManager {
private val webSockets: HashMap<String, WebSocket> = HashMap()
}

Step 3: Initialize WebSocket connections

To establish WebSocket connections, create a method in the WebSocketManager class called connect. This method should take a unique identifier and the WebSocket URL as parameters. Inside the method, create a new instance of WebSocket and add it to the webSockets map.

fun connect(identifier: String, url: String) {
val client = OkHttpClient()
val request = Request.Builder().url(url).build()
val webSocket = client.newWebSocket(request, WebSocketListener())
webSockets[identifier] = webSocket
}

Step 4: Implement WebSocketListener

Create a nested class inside the WebSocketManager class called WebSocketListener. This class should extend WebSocketListener and override its methods to handle WebSocket events.

private inner class WebSocketListener : okhttp3.WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
// Handle WebSocket connection opened event
}

override fun onMessage(webSocket: WebSocket, text: String) {
// Handle WebSocket message received event
}

override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
// Handle WebSocket connection closed event
}

override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
// Handle WebSocket connection failure event
}
}

Step 5: Add methods to send and receive messages

Inside the WebSocketManager class, add methods to send and receive messages through WebSocket connections. These methods should take the WebSocket identifier as a parameter and interact with the corresponding WebSocket instance.

fun send(identifier: String, message: String) {
val webSocket = webSockets[identifier]
webSocket?.send(message)
}

fun receive(identifier: String, callback: (String) -> Unit) {
val webSocket = webSockets[identifier]
webSocket?.let {
it.onMessage { _, text ->
callback.invoke(text)
}
}
}

Step 6: Connect and communicate with WebSocket connections

In your activity or fragment, create an instance of WebSocketManager and use it to connect to WebSocket URLs and send/receive messages.

val webSocketManager = WebSocketManager()

// Connect to WebSocket
webSocketManager.connect("ws1", "wss://example.com/ws1")
webSocketManager.connect("ws2", "wss://example.com/ws2")

// Send message
webSocketManager.send("ws1", "Hello from WebSocket 1")

// Receive message
webSocketManager.receive("ws2") { message ->
// Handle received message
}

That's it! You now have a WebSocketManager class that can handle multiple WebSocket connections in Kotlin Android. Feel free to extend the functionality as per your requirements.

Note: Don't forget to add the necessary permissions for internet access in your AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />