首页 > 解决方案 > 如何从 websocket 侦听器获取消息到不同的类?

问题描述

我目前正在尝试在 Raspberry Pi 和移动设备之间打开 WebRTC 通信通道。该应用程序正在 Kotlin 中开发,来自现有的演示:https ://github.com/shepeliev/webrtc-kmp-demo 。

对于信令服务器,我使用了以下示例中的代码:https ://kotlinlang.org/docs/mobile/connect-to-platform-specific-apis.html#example-send-and-receive-messages-from-a -websocket

这是我遇到问题的代码部分:

                appSocket.messageListener = {
                    Log.d(tag,"Mensagem recebida: $it")
                    msg = Json.decodeFromString(it)

                    when(msg.what){
                        "offer" -> {
                            val description = SessionDescription(SessionDescriptionType.Offer, msg.data)

                            localPeerConnection?.setRemoteDescription(description)
                            val answer = localPeerConnection?.createAnswer(OfferAnswerOptions())
                            Log.d(tag, "Answer to raspPi is: $answer")
                            appSocket.send(Json.encodeToString(answer))
                            localPeerConnection?.setLocalDescription(answer!!)

                        }
                    }
                }

每次收到消息时,我都需要 when 语句中的这些函数,但它们来自不同的上下文,并且只能在协程范围内调用。我得到错误:Suspension functions can be called only within coroutine body。协程主体在appSocket.messageListener.

为了澄清,我应该补充一下localPeerConnection?.setRemoteDescription(description)localPeerConnection?.createAnswer(OfferAnswerOptions())localPeerConnection?.setLocalDescription(answer!!)是有问题的挂起功能。如果我这样写代码:

                appSocket.messageListener = {
                    Log.d(tag,"Mensagem recebida: $it")
                    msg = Json.decodeFromString(it)

                }
                when(msg.what){
                    "offer" -> {
                        val description = SessionDescription(SessionDescriptionType.Offer, msg.data)

                        localPeerConnection?.setRemoteDescription(description)
                        val answer = localPeerConnection?.createAnswer(OfferAnswerOptions())
                        Log.d(tag, "Answer to raspPi is: $answer")
                        appSocket.send(Json.encodeToString(answer))
                        localPeerConnection?.setLocalDescription(answer!!)

                        }
                    }

挂起函数被正确调用,但当我收到 websocket 消息时不执行工作。有什么方法可以让我在每次appSocket.messagelistener收到消息时收听并when激活语句?或者我可以以某种方式将协程的上下文继承到内部appSocket.messagelistener并在那里有when语句吗?

谢谢您的帮助。

标签: kotlinwebrtckotlin-coroutines

解决方案


推荐阅读