如何使用协程使用 Kotlin 扫描本地 IP 地址

How to use coroutines to scan local IP addresses using Kotlin

我有一个扫描本地 IP 地址以连接到开放端口 8102 的应用程序。我已经能够获得正确的 IP 地址,但是需要很长时间,因为每个轮询都有 200 毫秒的超时。这是我成功获得它的最低值。

我想我的问题是有没有办法使用协程来拆分工作并更快地获取地址?现在大约需要 3 秒,我定位的地址只有 192.168.0.21。

这是我的代码:

<pre><code>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") }

理论上是可以的,但是你得测试一下

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")
    }

}