kotlin: implement automatic reconnection to websocket on failure

master
ALI Hamza 2019-10-12 14:21:15 +07:00
parent cc5e832859
commit 9332b2688e
No known key found for this signature in database
GPG Key ID: 7C608266BF384ADC
2 changed files with 17 additions and 8 deletions

@ -15,6 +15,7 @@ class TerraOceanPlugin: BukkitPlugin() {
listen(callback = ::onPlayerMovement) listen(callback = ::onPlayerMovement)
schedule(async = true) { schedule(async = true) {
instance.info("establishing connection to ${Settings.socketURL}...")
establishConnection() establishConnection()
} }
} }

@ -4,6 +4,7 @@ import com.terraocean.plugin.Settings
import com.terraocean.plugin.Strings import com.terraocean.plugin.Strings
import com.terraocean.plugin.instance import com.terraocean.plugin.instance
import hazae41.minecraft.kutils.bukkit.info import hazae41.minecraft.kutils.bukkit.info
import hazae41.minecraft.kutils.bukkit.schedule
import hazae41.minecraft.kutils.bukkit.warning import hazae41.minecraft.kutils.bukkit.warning
import okhttp3.* import okhttp3.*
import org.bukkit.Bukkit import org.bukkit.Bukkit
@ -13,14 +14,13 @@ val client = OkHttpClient.Builder()
.readTimeout(0, TimeUnit.MILLISECONDS) .readTimeout(0, TimeUnit.MILLISECONDS)
.build() .build()
lateinit var socket: WebSocket private var request = Request.Builder()
fun establishConnection() {
instance.info("establishing connection to ${Settings.socketURL}...")
val request = Request.Builder()
.url(Settings.socketURL) .url(Settings.socketURL)
.build() .build()
lateinit var socket: WebSocket
var wsFails = 0
fun establishConnection() {
socket = client.newWebSocket(request, WSListener()) socket = client.newWebSocket(request, WSListener())
} }
@ -67,9 +67,17 @@ class WSListener: WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) { override fun onOpen(webSocket: WebSocket, response: Response) {
instance.info("Socket connection established to $response.") instance.info("Socket connection established to $response.")
wsFails = 0
} }
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
TODO("Automatic reconnection") if (wsFails < 5) {
wsFails++
instance.warning("WS Fail: ${t.message}")
instance.info("Reconnecting to socket...")
}
instance.schedule(delay = 5, unit = TimeUnit.SECONDS) {
establishConnection()
}
} }
} }