我想在我的应用程序处于前台时打开一个套接字。我从这里使用 JAVA Api WebSocketClient:
所以我创建了一个管理器,它使用 onOpen、onClose、onMessage 和 onError 回调实现 WebSocketClient 接口,如下所示。我还有一个 pingPongTimer,所以我可以每隔 10 秒检查一次连接。该过程的周期是在应用程序生命周期中绑定的,所以当应用程序进入前台时我调用connect and startPingPongTimer
方法,而当它进入后台时调用kill and stopPingPongTimer
方法。WSS url 是来自 Amazon Web Services 的 webSocket。我的问题是,有时我调用 connect 方法,但我从来没有得到 onOpen 回调。我有时也会在断开连接并重新连接后收到 onClose 回调,因此我无法处理当前连接,因为我从前一个连接中获得了 onClose。
class FlowSocketManagerImpl: FlowSocketManager {
private var isFlowing: Boolean = false
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private var pingPongTimer = object: CountDownTimer(10000, 1000) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
println("On Finish")
send("Hello")
this.start()
}
}
private val mWebSocketClient = object : WebSocketClient(URI(Wss)) {
override fun onOpen(serverHandshake: ServerHandshake?) {
println("onOpen")
isFlowing = true
}
override fun onMessage(envelope: String?) {
println("onMessage $envelope")
}
override fun onClose(code: Int, reason: String, remote: Boolean) {
println("onClose $code $reason $remote")
isFlowing = false
socketBackOffStrategy(code)
}
override fun onError(e: Exception) {
e.printStackTrace()
println("onError ${e.message}")
isFlowing = false
}
}
@Throws(Exception::class)
override fun connect() {
mWebSocketClient.close()
mWebSocketClient.connectionLostTimeout = 10
if (mWebSocketClient.isClosed)
mWebSocketClient.connect()
}
override fun send(envelope: String) {
try {
mWebSocketClient.send(envelope)
} catch (e: WebsocketNotConnectedException) {
// ToDo Mark as unread
println("No connection")
}
}
override fun kill() {
if (mWebSocketClient.isOpen) {
mWebSocketClient.close()
}
}
private fun socketBackOffStrategy(code: Int) {
when (code) {
-1 -> {
// NetWork Unavailable
scope.launch {
delay(10000)
withContext(Dispatchers.Main) {
connect()
}
}
}
1000 -> {
// Successfully disconnected
}
1006 -> {
// 1006 The connection was closed because the other endpoint did not respond with a pong in time.
// For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection
if (mWebSocketClient.isClosed)
connect()
}
}
}
override fun startPingPongCountDown() {
pingPongTimer.start()
}
override fun stopPingPongCountDown() {
pingPongTimer.cancel()
}
}
用于我的目的的最佳方式或库是什么,或者我怎样才能使它更可靠、高效和稳定?谢谢