kotlin - 如何从 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
语句吗?
谢谢您的帮助。
解决方案
推荐阅读
- c# - 如何重置我的 Umbraco CMS 管理员密码?
- mysql - 错误代码:1064 - 您的 SQL 语法有错误
- swift - Swift / 用户隐私位置始终使用
- java - 尝试连接到 Azure Eventhub 时出错:AzureTokenCredentials / IllegalArgumentException: name
- javascript - 为什么我的对象内的箭头函数不起作用?
- android - 如何在 android xml 的组件/视图中添加 2 种样式
- azure-data-lake - 如何使用 python 脚本将 csv 文件从 GitHub 上传到 azure 数据湖
- mongodb - 使用 Nifi 查询 MongoDB
- module - nameError:名称“枢轴”未定义
- python - 使用输入参数进行棉花糖验证