From 4cd44811825b0a25b42e139192cac2c5aeea0328 Mon Sep 17 00:00:00 2001 From: CodeSteak Date: Wed, 5 Jun 2019 19:43:11 +0200 Subject: [PATCH] change Semantics of Client AutoConnect.searchServer. * now returns an optional * uses multiple trys. --- .../controller/net/AutoConnect.kt | 54 +++++++++++-------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/client/src/main/kotlin/org/hso/texturesyncclient/controller/net/AutoConnect.kt b/client/src/main/kotlin/org/hso/texturesyncclient/controller/net/AutoConnect.kt index 8105c6c..bfc670e 100644 --- a/client/src/main/kotlin/org/hso/texturesyncclient/controller/net/AutoConnect.kt +++ b/client/src/main/kotlin/org/hso/texturesyncclient/controller/net/AutoConnect.kt @@ -1,48 +1,60 @@ 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() {} +class AutoConnect private constructor() { companion object { @Throws(IOException::class) - fun search_server(mulicastAddr: String = "ff02::dd42:c0fe", port: Int = 10796, timeoutMs : Int = 4000): Connection { + fun searchServer( + mulicastAddr: String = "ff02::dd42:c0fe", + port: Int = 10796, + timeoutMs: Int = 400, + trys: Int = 10 + ): Connection? { val sock = DatagramSocket() try { sock.soTimeout = timeoutMs - val bytes = "TextureSync".toByteArray() + for (i in 0..trys) { + val bytes = "TextureSync".toByteArray() - sock.send( - DatagramPacket( - bytes, - 0, - bytes.size, - InetAddress.getByName(mulicastAddr), - port + 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) + // Response is PortNum in BE + val portData = ByteArray(2) + val response = DatagramPacket(portData, portData.size) - sock.receive(response) + try { + sock.receive(response) - // 2-Byte BE to Port Number - val port = (portData[0].toInt().shl(8)).or(portData[1].toInt()) + // 2-Byte BE to Port Number + val serverPort = (portData[0].toInt().shl(8)).or(portData[1].toInt()) - return Connection(response.address, port) - } catch ( e : Exception) { + return Connection(response.address, serverPort) + } catch (e: IOException) { + // Timed out + // NOP + } + } + } catch (e: Exception) { throw e } finally { sock.close() } + + return null } } } \ No newline at end of file