WebSocket Echo Client using Kotlin (Android)

nv-websocket-client library

  1. Add nv-websocket-client dependency in the module's build.gradle file:

app/build.gradle

dependencies {
    implementation 'com.neovisionaries:nv-websocket-client:2.10'
}
  1. Add INTERNET permission in the manifest file:

app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
  1. WebSocket echo client:

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.neovisionaries.ws.client.WebSocket
import com.neovisionaries.ws.client.WebSocketAdapter
import com.neovisionaries.ws.client.WebSocketFactory

class MainActivity : AppCompatActivity()
{
    private lateinit var ws: WebSocket

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

        val wsFactory = WebSocketFactory()
        ws = wsFactory.createSocket("wss://echo.websocket.org")

        ws.addListener(object : WebSocketAdapter() {
            override fun  onConnected(ws: WebSocket, headers: Map<String, List<String>>) {
                Log.d("MY_APP", "Connected")
                ws.sendText("Hello")
            }

            override fun onTextMessage(ws: WebSocket, text: String) {
                Log.d("MY_APP", "Message received: $text")
            }
        })

        ws.connectAsynchronously()
    }

    override fun onDestroy()
    {
        ws.disconnect()
        super.onDestroy()
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.