How to use Ktor BoundDatagramSocket to listen to incoming udp traffic

Viewed 565

I'm using ktor for a kotlin/native app. Currently I'm testing things out on the android side and because of that I have some code directly in the viewmodel. The app needs to listen to incoming udp datagrams but it doesn't seem to receive anything. What am I doing wrong in my implementation?

How I listen to the incoming data while testing:

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()
                    }
                }
        }

The code I actually wanted to get working:

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))
                    }
            }
        }

What I did in my terminal:

āžœ  platform-tools nc -u -c 192.168.1.130 40779
bla
bla
^C
0 Answers
Related