我正在使用 OkHttp 监听服务器消息,但它没有监听,检查后我不确定可能是什么问题,请检查下面。
这是我的网络Socket函数
private fun initWebSocket() {
val url = "wss://infomapapp.com/hmcpapi//wss?userId=4"
val request = Request.Builder()
.url(url)
.build()
val wsListener = object : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
// WebSocket connection opened
Log.d("WebSocket", "WebSocket connection opened $response")
}
override fun onMessage(webSocket: WebSocket, text: String) {
Log.d("WebSocket", text)
newChatsItem = parseMessage(text)
Log.d("WebSocket", "Parsed message: $newChatsItem")
runOnUiThread {
chatRecyclerView.scrollToPosition(chatList.size - 1)
}
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
// WebSocket is closing
Log.d("WebSocket", "WebSocket closing: $code / $reason")
webSocket.close(NORMAL_CLOSURE_STATUS, null)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
// WebSocket encountered an error
Log.e("WebSocket", "WebSocket error: ${t.message}")
}
}
webSocket = client.newWebSocket(request, wsListener)
}
这是我在 onCreate 中调用它的方式。
initWebSocket()。
这就是在活动开始时在 onCreate 中调用的方式
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
initWebSocket()
}
这也是预期的回应 {"serverMessage":true,"status":"已收到","error":"","info":"","clientSideMessageId":"1695284902791"} {"serverMessage":true,"status":"已保存","错误":"","信息":"","clientSideMessageId":"1695284902791"}
非常感谢
您需要字符串数据类型。如果您的服务器以二进制格式发送,则不会调用
onMessage
方法。您可以使用二进制数据类型覆盖另一个 onMessage
,或者如果您仅使用字符串数据类型,则覆盖二进制数据类型。此外,您可以根据需要更改服务器端的格式。这是一个例子:
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
Timber.i("message received: $bytes")
}
override fun onMessage(webSocket: WebSocket, text: String) {
super.onMessage(webSocket, text)
Timber.i("message received: $text")
}