发送Udp消息类
This commit is contained in:
parent
3a58f83928
commit
89ecd03f4f
34
app/src/main/java/top/rrricardo/motioncapture/UdpSender.kt
Normal file
34
app/src/main/java/top/rrricardo/motioncapture/UdpSender.kt
Normal 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
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user