工作笔记:Android中Websocket长链接使用说明

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

/**
 *    author : 吴明辉
 *    e-mail : 1412378121@qq.com
 *    date   : 2022/3/2510:16
 *    git    : https://gitee.com/yunianvh
 *    desc   : websocket工具类
 */
class WebSocketClient private constructor(url: String) {
    /**
     * 初始化OkHttpClient
     */
    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

/**
 *    author : 吴明辉
 *    e-mail : 1412378121@qq.com
 *    date   : 2022/3/2510:16
 *    git    : https://gitee.com/yunianvh
 *    desc   :
 */
interface SocketListener {
    fun onMessage(text: String)
    fun onClosed(code: Int, reason: String)
    fun onFailure(response: String)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玉念聿辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值