Websocket长链接使用说明
注:如果是直接用我的MVVM-base,那直接添加lib-network模块进行使用即可
添加依赖
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
调用
var socket = WebSocketClient.newInstance("")
socket.start(object : SocketListener {
override fun onMessage(text: String) {
}
override fun onClosed(code: Int, reason: String) {
}
override fun onFailure(response: String) {
}
})
socket.close()
代码块
package com.yangchoi.lib_network.websocket
import okhttp3.*
import java.util.concurrent.TimeUnit
class WebSocketClient private constructor(url: String) {
private fun initClient(url: String) {
if (url.isBlank()) return
try {
client = OkHttpClient.Builder().pingInterval(5, TimeUnit.SECONDS).build()
request = Request.Builder().url(url).build()
} catch (e: NoClassDefFoundError) {
}
}
fun start(listener: SocketListener) {
if (client == null || request == null) return
webSocket = client!!.newWebSocket(request!!, object : WebSocketListener() {
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
super.onClosed(webSocket, code, reason)
if (listener != null)
listener.onClosed(code, reason)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
super.onFailure(webSocket, t, response)
if (listener != null && response != null)
listener.onFailure(response!!.message())
}
override fun onMessage(webSocket: WebSocket, text: String) {
super.onMessage(webSocket, text)
if (listener != null)
listener.onMessage(text)
}
override fun onOpen(webSocket: WebSocket, response: Response) {
super.onOpen(webSocket, response)
}
})
}
fun close() {
if (webSocket != null) webSocket!!.close(1000, null)
if (client != null) client!!.dispatcher().executorService().shutdown()
}
fun send(msg: String) = webSocket!!.send(msg)
companion object {
fun newInstance(url: String): WebSocketClient {
return WebSocketClient(url)
}
private var request: Request? = null
private var client: OkHttpClient? = null
private var webSocket: WebSocket? = null
}
init {
initClient(url)
}
}
回调接口
package com.yangchoi.lib_network.websocket
interface SocketListener {
fun onMessage(text: String)
fun onClosed(code: Int, reason: String)
fun onFailure(response: String)
}