Implement AutoConnect
This commit is contained in:
@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user