Android SocketIO EngineIOException: websocket error

39 views Asked by At

I am trying to connect with the SocketIO, but I got this error from the Android side (iOS works): enter image description here

Here is what I am doing in the Android:

  override fun init() = callbackFlow {
    val accessToken = tokenStorage.accessToken ?: return@callbackFlow
    val option = IO.Options.builder()
      .setUpgrade(false)
      .setTransports(arrayOf(WebSocket.NAME))
      .setExtraHeaders(mapOf("Authorization" to listOf("Bearer ".plus(accessToken)))) // Without this I'll the the Unauthorized 401
      .build()
    socket = IO.socket(BuildConfig.WS_URL, option)

    socket.on(Socket.EVENT_CONNECT) {
      trySend(true)
    }

    socket.on(Socket.EVENT_CONNECT_ERROR) {
      Log.d("xxxx", "asSocketPayload error: ${it[0]}")
    }

    socket.on(DEFAULT_EVENT) {
      it[0].asSocketPayload()
    }

    socket.connect()

    awaitClose {
      socket.disconnect()
    }
  }

I am using the socket IO client 2.0.0

Thanks

1

There are 1 answers

0
Stevie On

It seems the client doesn't support adding a header. So I tried using the OkHttpClient instead. It's working like a charm. Here is the short version of it:

 override fun init() = callbackFlow {
    val accessToken = tokenStorage.accessToken ?: return@callbackFlow

    val client = OkHttpClient()
    val request = Request.Builder()
      .url(BuildConfig.WS_URL)
      .addHeader("Authorization", "Bearer $accessToken")
      .build()

    val webSocketListener = object : WebSocketListener() {
      override fun onOpen(webSocket: okhttp3.WebSocket, response: Response) {
        trySend(true)
      }

      override fun onMessage(webSocket: okhttp3.WebSocket, text: String) {
        // Handle incoming message
        Log.d("xxxx", "asSocketPayload: $text")
      }

      override fun onClosing(webSocket: okhttp3.WebSocket, code: Int, reason: String) {
        // Handle closing connection
        Log.d("xxxx", "asSocketPayload: $reason")
      }

      override fun onFailure(webSocket: okhttp3.WebSocket, t: Throwable, response: Response?) {
        // Handle failure
        Log.d("xxxx", "asSocketPayload: $t -- $response")
      }
    }

    client.newWebSocket(request, webSocketListener)

    awaitClose {
      client.dispatcher.executorService.shutdown()
    }
  }

Note that: In this case the socket enpoint should use wss:// instead of https:// . I'll mark this as an answer to this question. So if you have a solution to use SocketIO client, please let us know below. Thanks!