发送Udp消息类

This commit is contained in:
jackfiled 2023-01-30 17:55:59 +08:00
parent 3a58f83928
commit 89ecd03f4f

View File

@ -0,0 +1,34 @@
package top.rrricardo.motioncapture
import android.util.Log
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
class UdpSender(val targetIp: String, val targetPort: Int) {
private val datagramSocket = DatagramSocket()
private val tag = "UdpSender"
private var closed = false
fun sendMessage(data: ByteArray) {
if (closed) {
Log.e(tag, "Udp sender has been closed!")
return
}
val packet = DatagramPacket(data, data.size, InetAddress.getByName(targetIp), targetPort)
try {
datagramSocket.send(packet)
} catch (e: java.lang.Exception) {
e.printStackTrace()
Log.e(tag, "UDP send error: $e")
}
}
fun close() {
datagramSocket.close();
closed = true
}
}