Help us understand the problem. What is going on with this article?

Kotlin UDP ソケット通信

More than 1 year has passed since last update.

はじめに

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)
unpi
大阪のエンジニアです。 メインはAndroidです。
i-enter
「効果」をつねに提供します。スマホアプリ開発No.1の実績。最新のIoTに対応した開発も行います。
https://www.i-enter.co.jp/
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした