
























@@ -1,12 +1,14 @@
11package ai.openclaw.app.gateway
2233import android.util.Log
4+import kotlinx.coroutines.CancellationException
45import kotlinx.coroutines.CompletableDeferred
56import kotlinx.coroutines.CoroutineScope
67import kotlinx.coroutines.Dispatchers
78import kotlinx.coroutines.Job
89import kotlinx.coroutines.TimeoutCancellationException
910import kotlinx.coroutines.cancelAndJoin
11+import kotlinx.coroutines.channels.Channel
1012import kotlinx.coroutines.delay
1113import kotlinx.coroutines.isActive
1214import kotlinx.coroutines.launch
@@ -384,6 +386,22 @@ class GatewaySession(
384386private val client: OkHttpClient = buildClient()
385387private var socket: WebSocket? = null
386388private val loggerTag = "OpenClawGateway"
389+private val incomingMessages = Channel<String>(Channel.UNLIMITED)
390+private val messagePumpJob =
391+ scope.launch(Dispatchers.IO) {
392+for (text in incomingMessages) {
393+try {
394+ handleMessage(text)
395+ } catch (err: CancellationException) {
396+throw err
397+ } catch (err: Throwable) {
398+Log.w(
399+ loggerTag,
400+"gateway message handling failed: ${err.message ?: err::class.java.simpleName}",
401+ )
402+ }
403+ }
404+ }
387405388406val remoteAddress: String = formatGatewayAuthority(endpoint.host, endpoint.port)
389407@@ -475,6 +493,11 @@ class GatewaySession(
475493476494fun closeQuietly() {
477495if (isClosed.compareAndSet(false, true)) {
496+ incomingMessages.close()
497+ messagePumpJob.cancel()
498+if (!connectDeferred.isCompleted) {
499+ connectDeferred.completeExceptionally(IllegalStateException("Gateway closed"))
500+ }
478501 socket?.close(1000, "bye")
479502 socket = null
480503 closedDeferred.complete(Unit)
@@ -519,7 +542,7 @@ class GatewaySession(
519542webSocket: WebSocket,
520543text: String,
521544 ) {
522-scope.launch { handleMessage(text) }
545+incomingMessages.trySend(text)
523546 }
524547525548override fun onFailure(
@@ -531,6 +554,7 @@ class GatewaySession(
531554 connectDeferred.completeExceptionally(t)
532555 }
533556if (isClosed.compareAndSet(false, true)) {
557+ incomingMessages.close()
534558 failPending()
535559 closedDeferred.complete(Unit)
536560 onDisconnected("Gateway error: ${t.message ?: t::class.java.simpleName}")
@@ -546,6 +570,7 @@ class GatewaySession(
546570 connectDeferred.completeExceptionally(IllegalStateException("Gateway closed: $reason"))
547571 }
548572if (isClosed.compareAndSet(false, true)) {
573+ incomingMessages.close()
549574 failPending()
550575 closedDeferred.complete(Unit)
551576 onDisconnected("Gateway closed: $reason")
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。