Server Error on connection using Socket IO

42 views Asked by At

I am using the Socket.io for my connection to the server with wss protocol , below is my code i am facing issues as server error. Same URL with the WebSocket i am not facing any issue socket gets connected, kindly let me know what i am missing from my below code

package com.example.socketapplication
import android.util.Log
import io.socket.client.IO
import io.socket.client.Socket
import java.lang.Exception
import java.net.URISyntaxException


class SocketManager {
    private var socket: Socket? = null
    private var url = "wss://xyz.com/primus/?_primuscb=dBAJyfE&EIO=4&transport=websocket&sid=sp1BWFXgxS2hBz7YAFQt&t=WZKvQcZ&b64=1"
    init {
        try {
            socket = IO.socket(url)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun connect() {
        socket?.connect()
        socket?.on(Socket.EVENT_CONNECT_ERROR) {

            Log.i("SocketConnection", "Not connected ${it.first().toString()}")
            // Now you can safely use socket.connected()
        }
    }

    fun disconnect() {
        socket?.disconnect()
    }

    fun isConnected(): Boolean {
        return socket?.connected() ?: false
    }

    fun onMessageReceived(listener: (String) -> Unit) {
        socket?.on("message") { args ->
            val message = args[0] as String
            listener.invoke(message)
        }
    }

    fun sendMessage(message: String) {
        socket?.emit("message", message)
    }
}

Dependency Used:

implementation ("io.socket:socket.io-client:2.1.0")

Calling Part

private val socketManager = SocketManager()
    socketManager.connect()
1

There are 1 answers

2
Gabe Sechan On

The library you're trying to use doesn't support that protocol. From the docs at https://socket.io/docs/v4/

What Socket.IO is not caution

Socket.IO is NOT a WebSocket implementation.

Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.

// WARNING: the client will NOT be able to connect! const socket = io("ws://echo.websocket.org");

Also from the same page:

caution

Socket.IO is not meant to be used in a background service for mobile applications.

The Socket.IO library keeps an open TCP connection to the server, which may result in a high battery drain for your users. Please use a dedicated messaging platform like FCM for this use case.

While there are ways you can use it, for the most part you should avoid websockets in mobile programming. Particularly if you expect the app to ever be backgrounded.