1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
| package com.xhkjedu.zxs_android.ws
import android.util.Log import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.WebSocket import java.util.concurrent.TimeUnit import kotlin.math.min
object ZWsManager { private var wsUrl = "" private var webSocket: WebSocket? = null private val client = OkHttpClient.Builder() .pingInterval(20, TimeUnit.SECONDS) .build()
private var isManualClose = false
private var currentReconnectDelay = 1_000L
private const val reconnectMaxDelay: Long = 30_000
private var reconnectCount = 0
private const val MAX_RECONNECT_COUNT = 10
private var reconnectJob: Job? = null
private val listeners = mutableListOf<ZWsListener>()
fun resetParas() { reconnectCount = 0 currentReconnectDelay = 1_000L isManualClose = false }
fun connect(url: String = "", isReConnect: Boolean = false) { if (url.isNotEmpty()) { wsUrl = url }
if (webSocket != null) { webSocket?.close(1000, "Client closed") webSocket = null } if (!isReConnect) { resetParas() }
if (wsUrl.isEmpty()) { return }
val request = Request.Builder().url(wsUrl).build() webSocket = client.newWebSocket(request, object : okhttp3.WebSocketListener() { override fun onOpen(webSocket: WebSocket, response: Response) { Log.w("WebSocket", "连接成功") notifyOnConnected() }
override fun onMessage(webSocket: WebSocket, text: String) { notifyOnMessage(text) }
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { Log.e("WebSocket", "连接失败: ${t.message}", t) this@ZWsManager.webSocket = null
if (reconnectCount >= MAX_RECONNECT_COUNT) { Log.w("WebSocket", "已达到最大重连次数 ($MAX_RECONNECT_COUNT),停止重连") notifyOnFailure(t) return }
notifyOnFailure(t)
if (!isManualClose) { scheduleReconnect() } else { Log.w("WebSocket", "正常退出不再重连") } }
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { Log.w("WebSocket", "连接关闭: $code - $reason") this@ZWsManager.webSocket = null notifyOnClosed(code, reason)
if (reconnectCount >= MAX_RECONNECT_COUNT) { Log.w("WebSocket", "已达到最大重连次数,停止重连") return }
if (!isManualClose) { scheduleReconnect() } else { Log.w("WebSocket", "正常退出不再重连") } } }) }
fun disconnect() { isManualClose = true
val oldJob = reconnectJob reconnectJob = null oldJob?.cancel()
webSocket?.close(1000, "Client closed") webSocket = null
Log.w("WebSocket", "连接已断开") }
fun sendMessage(text: String): Boolean { return webSocket?.send(text) ?: false }
fun registerListener(listener: ZWsListener) { if (!listeners.contains(listener)) { listeners.add(listener) } }
fun unregisterListener(listener: ZWsListener) { listeners.remove(listener) }
private fun notifyOnConnected() { Log.w("WebSocket", "通知监听器:连接成功") listeners.forEach { it.onConnected() } }
private fun notifyOnMessage(message: String) { listeners.forEach { it.onMessageReceived(message) } }
private fun notifyOnFailure(throwable: Throwable) { Log.e("WebSocket", "通知监听器:连接失败", throwable) listeners.forEach { it.onFailure(throwable) } }
private fun notifyOnClosed(code: Int, reason: String) { Log.w("WebSocket", "通知监听器:连接关闭 ($code - $reason)") listeners.forEach { it.onClosed(code, reason) } }
@OptIn(DelicateCoroutinesApi::class) private fun scheduleReconnect() { if (isManualClose) return
reconnectCount++ Log.w("WebSocket", "计划在 ${currentReconnectDelay}ms 后重连 (第 $reconnectCount 次)")
val newJob = GlobalScope.launch(Dispatchers.IO) { try { delay(currentReconnectDelay)
if (isManualClose) { Log.w("WebSocket", "重连被取消") return@launch }
if (webSocket != null) { Log.w("WebSocket", "已有活跃连接,跳过重连") return@launch }
if (reconnectCount >= MAX_RECONNECT_COUNT) { Log.w("WebSocket", "已达到最大重连次数,停止重连") return@launch }
currentReconnectDelay = min(currentReconnectDelay * 2, reconnectMaxDelay) connect(isReConnect = true)
} catch (e: InterruptedException) { Log.w("WebSocket", "重连被中断") Thread.currentThread().interrupt() } catch (e: Exception) { Log.e("WebSocket", "重连任务取消") reconnectCount-- currentReconnectDelay = min(currentReconnectDelay * 2, reconnectMaxDelay) } }
reconnectJob = newJob } }
interface ZWsListener { fun onConnected() {} fun onMessageReceived(message: String) {} fun onFailure(error: Throwable) {} fun onClosed(code: Int, reason: String) {} }
|