我有一個掃描本地 IP 地址以連接到開放埠 8102 的應用程式。我已經能夠獲得正確的 IP 地址,但這需要很長時間,因為每次輪詢的超時時間為 200 毫秒。這是我能夠成功獲得的最低值。
我想我的問題是有沒有辦法使用協程來拆分作業并更快地獲得地址?現在大約需要 3 秒,我的目標地址只有 192.168.0.21。
這是我的代碼:
fun init() = GlobalScope.launch(Dispatchers.IO) {
//Get local ip
DatagramSocket().use { socket ->
socket.connect(InetAddress.getByName("8.8.8.8"), 10002)
ip = socket.getLocalAddress().getHostAddress().split(".") as MutableList<String>
}
//Go through local addresses to find receiver
txtOutput.text = ip.toString()
prefix = ip[0] "." ip[1] "." ip[2] "."
var i = 1
do {
try {
client = Socket()
client.connect(InetSocketAddress(prefix i.toString(), 8102), 200)
} catch (e: Exception) {
print(e.toString())
i
}
} while (!(client.isConnected) or (i > 254))
targetIP = prefix i.toString()
client = Socket()
try{
client.connect(InetSocketAddress(targetIP, 8102), 150)
if(client.isConnected){
client.keepAlive = true}}
catch (e:IOException){
cancel("Could not connect")
}
uj5u.com熱心網友回復:
理論上是可行的,但你必須測驗它
fun init() = GlobalScope.launch(Dispatchers.IO) {
//Get local ip
DatagramSocket().use { socket ->
socket.connect(InetAddress.getByName("8.8.8.8"), 10002)
ip = socket.getLocalAddress().getHostAddress().split(".") as MutableList<String>
}
//Go through local addresses to find receiver
txtOutput.text = ip.toString()
prefix = ip[0] "." ip[1] "." ip[2] "."
// var i = 1
// do {
// try {
// client = Socket()
// client.connect(InetSocketAddress(prefix i.toString(), 8102), 200)
// } catch (e: Exception) {
// print(e.toString())
// i
// }
// } while (!(client.isConnected) or (i > 254))
///#########
val answer= Channel<Int>()
for (i in 0..254){
launch {
try {
client = Socket()
client.connect(InetSocketAddress(prefix i.toString(), 8102), 200)
answer.send(i)
}catch (e:Exception){ }
}
}
val i=answer.receive()
///#########
targetIP = prefix i.toString()
client = Socket()
try {
client.connect(InetSocketAddress(targetIP, 8102), 150)
if (client.isConnected) {
client.keepAlive = true
}
} catch (e: IOException) {
cancel("Could not connect")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/439205.html
上一篇:mysql事務、隔離級別
下一篇:PHP:接收UDP廣播
