I want to use kotlin for UDP communication.

Asked 1 months ago, Updated 1 months ago, 3 views

As per the title, I would like to use kotlin for UDP socket communication.
I can't find any samples, so could someone tell me?

android kotlin

2022-09-30 14:04

1 Answers

If you don't mind the sample, I made SNTP communication using kotlin.
The contents of the data are not good enough.

import java.net.*

funmain(args:Array<String>){
    valsocket=DatagramSocket()
    socket.connect(Inet4Address.getByName("192.168.0.132"),123)

    valdata=ByteArray(128)
    val header=(0shl30) or (4shl27) or (3shl24) or (15shl16) or (4shl8)
    data[0] = (header shr24).toByte()
    data[1] = (header shr16).toByte()
    data[2] = (header shr8).toByte()
    data[3] = (header shr0).toByte()

    valpkt = DatagramPacket (data, 4*12)
    socket.send(pkt)

    pkt.length=data.size
    socket.receive(pkt)

    System.out.println(data.copyOf(pkt.length).joinToString(
            separator=",
            transform={b->String.format("%02x",b)}
    ))
}

I think what I'm doing is the same as when I was in Java.


2022-09-30 14:04

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.