Search code examples
androidandroid-studiosocketsudpudpclient

How to receive data through UPD socket in Android Application


I have read through a number of different posts and questions, and it seems to me that this should be relatively easy to get right. I managed to send a UDP packet to the correct (address, port) using one socket object but can only read the message using the same socket object. This behaviour can be seen below in my code along with the corresponding output:

    GlobalScope.launch {
        val messageStr = "Hello Android!"
        val s = DatagramSocket(null)
        s.reuseAddress = true
        s.broadcast = true
        s.bind(InetSocketAddress(6670))
        s.soTimeout = 1500
        var local = InetAddress.getByName("0.0.0.0")
        val msg_length = messageStr.length
        val messageSent = messageStr.toByteArray()
        val p = DatagramPacket(messageSent, msg_length, local, 6670)
        s.send(p)

        val sRec = DatagramSocket(null)
        sRec.reuseAddress = true
        sRec.broadcast = true
        sRec.bind(InetSocketAddress(6670))
        Log.d("testUDP", "SoTimeOut:${sRec.soTimeout}")
        sRec.soTimeout = 1500
        var data = "Packet0"
        var udpPacket = DatagramPacket(
            data.toByteArray(),
            data.length,
            InetAddress.getByName("0.0.0.0"),
            6670
        )
        sRec.send(udpPacket)

        data = "Packet1"
        udpPacket = DatagramPacket(
            data.toByteArray(),
            data.length,
            InetAddress.getByName("0.0.0.0"),
            6670
        )
        sRec.send(udpPacket)

        data = "Packet2"
        udpPacket = DatagramPacket(
            data.toByteArray(),
            data.length,
            InetAddress.getByName("0.0.0.0"),
            6670
        )
        sRec.send(udpPacket)

        var text: String
        val messageRec = ByteArray(1500)
        val pRec = DatagramPacket(messageRec, messageRec.size)

        var count = 0
        while(count < 3){
            try{
                sRec.receive(pRec)
                text = String(messageRec, 0, pRec.length)
                Log.d("testUDP", "message:$text")
            } catch (e: Exception){
                e.printStackTrace()
            }
            count +=1
        }

        s.close()
        sRec.close()
    }

D/testUDP: message:Packet0

D/testUDP: message:Packet1

D/testUDP: message:Packet2

As you can see, the socket object sRec does not receive the message sent by the socket object s, even though they both bind to the same (address, port). Can someone please help me understand what I am missing. Thank you very much for your time and help in advance.


Solution

  • Server and client should be on two different threads to ensure one is not blocking the other.