我正在将ktor用于kotlin / native应用程序。目前,我正在android方面进行测试,因此我在viewmodel中直接添加了一些代码。该应用程序需要监听传入的udp数据报,但似乎什么也没收到。我在执行过程中做错了什么?
我在测试时如何监听传入的数据:
viewModelScope.launch(Dispatchers.IO) {
aSocket(ActorSelectorManager(Dispatchers.IO)).udp()
.bind(InetSocketAddress("localhost", 40779))
.use { udpSocket ->
Log.d("hereUDP", udpSocket.localAddress.toString())
try {
while (!udpSocket.isClosed) {
val datagram = udpSocket.receive()
Log.d("hereUDP", "received")
val line = datagram.packet.readText()
Log.d("hereUDP", line)
if (line.toLowerCase() == "q")
udpSocket.close()
}
Log.d("hereUDP", "closed")
} catch (e:Throwable){
Log.d("hereUDP", "something went wrong", e)
udpSocket.close()
}
}
}
我实际上想要开始工作的代码:
coroutineScope {
launch(Dispatchers.IO + socket!!.socketContext) {
socket?.incoming
?.consumeEach {
val data = it.packet.readBytes()
val address = it.address as InetSocketAddress
listener?.onReceive(data, HostEndpoint(address.hostName))
}
}
}
我在终端机中所做的事情:
➜ platform-tools nc -u -c 192.168.1.130 40779
bla
bla
^C