Home > Net >  Not able to receive acknowledgement from server in socket.io in android kotlin
Not able to receive acknowledgement from server in socket.io in android kotlin

Time:06-16

I successfully make connection between client server but problem is that one of my event chat:enter cannot be acknowledge from server in android and it is working fine in frontend , just problem in android.

for socket connection

 fun connectWithChatServer(message: Message, onSocketIOEventListener: Listeners.OnSocketIOEventListener) {
    try {
        if (message.chatConnectionInfo != null) {
            val token: String = message.chatConnectionInfo?.token!!
            try {
                val opts = IO.Options()
                opts.forceNew = true
                opts.query = "{token : '$token'}"
                opts.transports = arrayOf("websocket")
                opts.path = "/chatsignal"
                mSocket = IO.socket(message.chatConnectionInfo?.connectionUrl.toString(), opts)
                makeConnection()
            } catch (e: Exception) {
                e.printStackTrace()
                Log.d("fail", "Failed to connect")
            }
        }
    } catch (e: URISyntaxException) {
        throw RuntimeException(e)
    }
}
private fun makeConnection() {
    if (mSocket != null) {
        mSocket?.connect()
        registerConnectionAttributes()
    }
}
private fun registerConnectionAttributes() {
    try {
        if (mSocket != null) {
            mSocket?.on(Socket.EVENT_CONNECT, onConnect)
           
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
}

onConnect emitter

private var onConnect = Emitter.Listener {
        mSocket!!.emit("chat:enter", "{}", Ack { args ->
            Constants.printDebug(logTag, "Ack ${args[0]}")
            val text = args[0].toString()
        })
    }

CodePudding user response:

you have to register a listener before connecting

so your makeConnection should be changed to that

private fun makeConnection() {
    if (mSocket != null) {
        registerConnectionAttributes()
        mSocket?.connect()
    }
}

CodePudding user response:

if (message.chatConnectionInfo != null) {
        val token: String = message.chatConnectionInfo?.token!!
        try {
            val opts = IO.Options()
            opts.forceNew = true
            opts.query = "token=$token"
            opts.transports = arrayOf("websocket")
            opts.path = "/chatsignal"
            mSocket = IO.socket(message.chatConnectionInfo?.connectionUrl.toString(), opts)
            makeConnection()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("fail", "Failed to connect")
        }
    }

I solved by just need to change opts.query = "{token : '$token'}" to opts.query = "token=$token" in connectWithChatServer()

  • Related