Confirm data sent through socket had been received in the server

546 views Asked by At

I defined the websocket in my android app as below:

package com.oryx.geoop

import android.content.Context
import androidx.lifecycle.MutableLiveData
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.lang.Exception
import java.net.URI

lateinit var mWebSocketClient: WebSocketClient


class SocketClient {
    val uri = URI("ws://10.0.2.2:8080/ws")


    val message = MutableLiveData<String>()

    fun connectWebSocket(context: Context) {
        // Setup stuff

        mWebSocketClient = object : WebSocketClient(uri) {
            override fun onError(ex: Exception?) {
                // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onClose(code: Int, reason: String?, remote: Boolean) {
                // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onOpen(serverHandshake: ServerHandshake) {
                // Opened do some stuff
            }

            override fun onMessage(s: String) {
                message.postValue(s)
            }
        }
        mWebSocketClient.connect()
    }
}

And I use it to send data to the server as below, after checking the socket is opened or not:

if (mWebSocketClient.isOpen) {
      mWebSocketClient.send(jObj.toString())
} else {
      client.connectWebSocket(p0)
      mWebSocketClient.send(data)
}

But still have doubt as connection may be cut somewhere in between, so need the server to send back a confirmation note to the android app.

How can I make the app understand the returned msg from the server as a confirmation of receiving the data the mobile itself sent. Let's say the msg sent back from the server is "confirmed, $data"

1

There are 1 answers

0
theapache64 On BEST ANSWER

On every message you send to the server, the server can send back a confirmation message easily. The method name depends on the server stack you use. Mostly, it's something like client.sendMessage(yourMessage)

Now, let's answer your question which you asked in the comments section.

How can I make the android app understand this msg is a confirmation one, not a normal one ?

Rather than passing raw text, you can do the communication in JSON

For example,

You can send normal response in below format

{
  "type": "NORMAL",
  "id": "someUniqueIdOfTheMessage",
  "message": "This is some normal message"
}

and for the confirmation,the server can send back something like this

{
  "type": "CONFIRMATION",
  "id": "someUniqueIdOfTheMessage"
}