https://stackoverflow.com/q/55533832/5105007
class UdpSendActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_udp_send)
Thread(::runTest1).start()
Thread(::runTest2).start()
}
fun runTest1():Unit {
val dstAddressList = List(50 ){
Inet4Address.getByName("192.168.1.${10 + it}")
}
val srcSocket = DatagramSocket()
val byteArray = ByteArray(500)
val startMs = System.currentTimeMillis()
for (dstAddress in dstAddressList) {
val packet = DatagramPacket(byteArray, 0, byteArray.size, dstAddress, 55555)
srcSocket.send(packet)
srcSocket.send(packet)
srcSocket.send(packet)
srcSocket.send(packet)
}
val costMs = System.currentTimeMillis() - startMs
Log.e("UdpSendActivity", "#A $costMs ms")
}
fun runTest2():Unit {
val dstAddressList = List(50 ){
Inet4Address.getByName("192.168.1.${10 + it}")
}
// val srcSocket = DatagramSocket()
val byteArray = ByteArray(500)
val startMs = System.currentTimeMillis()
for (dstAddress in dstAddressList) {
val packet = DatagramPacket(byteArray, 0, byteArray.size, dstAddress, 55555)
// the diffrent line
val srcSocket = DatagramSocket()
srcSocket.send(packet)
srcSocket.send(packet)
srcSocket.send(packet)
srcSocket.send(packet)
}
val costMs = System.currentTimeMillis() - startMs
Log.e("UdpSendActivity", "#B $costMs ms")
}
}
log:
E/UdpSendActivity: #B 23 ms
E/UdpSendActivity: #A 1507 ms
两个测试的区别在于使用一个 DatagramSocket 发送给所有的目的地址 还是 每个目的地址创建一个新的 DatagramSocket 来发送,日志显示前者速度非常慢。
1
inoizyz 2019-04-08 15:14:22 +08:00 via Android
每次循环都使用一个新的 socket 那就不用管之前那个 socket 的状态,可以直接用吧?如果用旧的,那上一个包没发完会扔掉重新开始发当前的包吗,DatagramSocket.send 是同步的吧?
|