我在我的 android 应用程序中定义了 websocket,如下所示:
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()
}
}
在检查套接字是否打开后,我使用它向服务器发送数据,如下所示:
if (mWebSocketClient.isOpen) {
mWebSocketClient.send(jObj.toString())
} else {
client.connectWebSocket(p0)
mWebSocketClient.send(data)
}
但仍然有疑问,因为连接可能会在两者之间的某处被切断,因此需要服务器向 android 应用发送回确认信息。
我怎样才能让应用程序理解从服务器返回的消息,以确认接收到手机本身发送的数据。假设从服务器发回的味精是"confirmed, $data"