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)
schedule(async = true) {
instance.info("establishing connection to ${Settings.socketURL}...")
establishConnection()
}
}

@ -4,6 +4,7 @@ import com.terraocean.plugin.Settings
import com.terraocean.plugin.Strings
import com.terraocean.plugin.instance
import hazae41.minecraft.kutils.bukkit.info
import hazae41.minecraft.kutils.bukkit.schedule
import hazae41.minecraft.kutils.bukkit.warning
import okhttp3.*
import org.bukkit.Bukkit
@ -13,14 +14,13 @@ val client = OkHttpClient.Builder()
.readTimeout(0, TimeUnit.MILLISECONDS)
.build()
private var request = Request.Builder()
.url(Settings.socketURL)
.build()
lateinit var socket: WebSocket
var wsFails = 0
fun establishConnection() {
instance.info("establishing connection to ${Settings.socketURL}...")
val request = Request.Builder()
.url(Settings.socketURL)
.build()
socket = client.newWebSocket(request, WSListener())
}
@ -44,7 +44,7 @@ fun processMessage(msg: List<String>) {
Bukkit.getPlayer(msg[1])?.kickPlayer(Strings.voteKick)
}
"whitelistadd" -> {
instance.server.run {
instance.server.run {
getOfflinePlayer(msg[1]).isWhitelisted = true
}
}
@ -60,16 +60,24 @@ fun processMessage(msg: List<String>) {
}
}
class WSListener: WebSocketListener() {
class WSListener : WebSocketListener() {
override fun onMessage(webSocket: WebSocket, text: String) {
processMessage(text.split(' '))
}
override fun onOpen(webSocket: WebSocket, response: Response) {
instance.info("Socket connection established to $response.")
wsFails = 0
}
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()
}
}
}