简体   繁体   中英

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

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()
        })
    }

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()
    }
}
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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM