Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
8
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

Organization

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)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
8
Help us understand the problem. What are the problem?