LoginSignup
4
8

More than 5 years have passed since last update.

Kotlin UDP ソケット通信

Last updated at Posted at 2018-03-28

はじめに

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)
4
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
8