Implement AutoConnect

This commit is contained in:
2019-06-05 17:05:34 +02:00
parent 99ef2a8edc
commit adc8725a36
2 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,48 @@
package org.hso.texturesyncclient.controller.net
import java.io.IOException
import java.lang.Exception
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
class AutoConnect {
private constructor() {}
companion object {
@Throws(IOException::class)
fun search_server(mulicastAddr: String = "ff02::dd42:c0fe", port: Int = 10796, timeoutMs : Int = 4000): Connection {
val sock = DatagramSocket()
try {
sock.soTimeout = timeoutMs
val bytes = "TextureSync".toByteArray()
sock.send(
DatagramPacket(
bytes,
0,
bytes.size,
InetAddress.getByName(mulicastAddr),
port
)
)
// Response is PortNum in BE
val portData = ByteArray(2)
val response = DatagramPacket(portData, portData.size)
sock.receive(response)
// 2-Byte BE to Port Number
val port = (portData[0].toInt().shl(8)).or(portData[1].toInt())
return Connection(response.address, port)
} catch ( e : Exception) {
throw e
} finally {
sock.close()
}
}
}
}