WebSocket Echo Client using Java (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.java

package com.example.app;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity
{
    private WebSocket ws;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebSocketFactory wsFactory = new WebSocketFactory();

        try {
            ws = wsFactory.createSocket("wss://echo.websocket.org");

            ws.addListener(new WebSocketAdapter() {
                @Override
                public void onConnected(WebSocket ws, Map<String, List<String>> headers) {
                    Log.d("MY_APP", "Connected");
                    ws.sendText("Hello");
                }

                @Override
                public void onTextMessage(WebSocket ws, String text) {
                    Log.d("MY_APP", "Message received: " + text);
                }
            });

            ws.connectAsynchronously();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy()
    {
        ws.disconnect();
        super.onDestroy();
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.