Android
Kotlin

Kotlin UDP ソケット通信

はじめに

DatagramSocketを利用した、UDPの送受信プログラムを書いてみた。

送信

実装
fun send(host: String, port: Int, data: ByteArray, senderPort: Int = 0): Boolean {
    var ret = false
    var socket: DatagramSocket? = null
    try {
        socket = DatagramSocket(senderPort)
        val address = InetAddress.getByName(host)
        val packet = DatagramPacket(data, data.size, address, port)
        socket.send(packet)
        ret = true
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        socket?.close()
    }
    return ret
}
呼び出し元
val host = "localhost"
val port = 12345
val sendData = "hoge".toByteArray()

send(host, port, sendData)

受信

実装
fun receive(port: Int, size: Int): ByteArray {
    val ret = ByteArray(size)
    var socket: DatagramSocket? = null
    try {
        socket = DatagramSocket(port)
        val packet = DatagramPacket(ret, ret.size)
        socket.receive(packet)
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        socket?.close()
    }
    return ret
}
呼び出し元
val port = 54321
val bufferSize = 256

val receiveData = receive(port, bufferSize)