120 lines
2.6 KiB
Kotlin
120 lines
2.6 KiB
Kotlin
package nl.astraeus.vst.string.ws
|
|
|
|
import kotlinx.browser.window
|
|
import nl.astraeus.vst.string.PatchDTO
|
|
import nl.astraeus.vst.string.audio.VstStringWorklet
|
|
import nl.astraeus.vst.string.midi.Midi
|
|
import nl.astraeus.vst.string.view.MainView
|
|
import org.w3c.dom.MessageEvent
|
|
import org.w3c.dom.WebSocket
|
|
import org.w3c.dom.events.Event
|
|
|
|
object WebsocketClient {
|
|
var websocket: WebSocket? = null
|
|
var interval: Int = 0
|
|
|
|
fun connect(onConnect: () -> Unit) {
|
|
close()
|
|
|
|
websocket = if (window.location.hostname.contains("localhost") || window.location.hostname.contains("192.168")) {
|
|
WebSocket("ws://${window.location.hostname}:${window.location.port}/ws")
|
|
} else {
|
|
WebSocket("wss://${window.location.hostname}/ws")
|
|
}
|
|
|
|
websocket?.also { ws ->
|
|
ws.onopen = {
|
|
onOpen(ws, it)
|
|
onConnect()
|
|
}
|
|
ws.onmessage = { onMessage(ws, it) }
|
|
ws.onclose = { onClose(ws, it) }
|
|
ws.onerror = { onError(ws, it) }
|
|
}
|
|
}
|
|
|
|
fun close() {
|
|
websocket?.close(-1, "Application closed socket.")
|
|
}
|
|
|
|
fun onOpen(
|
|
ws: WebSocket,
|
|
event: Event
|
|
) {
|
|
interval = window.setInterval({
|
|
val actualWs = websocket
|
|
|
|
if (actualWs == null) {
|
|
window.clearInterval(interval)
|
|
|
|
console.log("Connection to the server was lost!\\nPlease try again later.")
|
|
reconnect()
|
|
}
|
|
}, 10000)
|
|
}
|
|
|
|
fun reconnect() {
|
|
val actualWs = websocket
|
|
|
|
if (actualWs != null) {
|
|
if (actualWs.readyState == WebSocket.OPEN) {
|
|
console.log("Connection to the server was lost!\\nPlease try again later.")
|
|
} else {
|
|
window.setTimeout({
|
|
reconnect()
|
|
}, 1000)
|
|
}
|
|
} else {
|
|
connect {}
|
|
|
|
window.setTimeout({
|
|
reconnect()
|
|
}, 1000)
|
|
}
|
|
}
|
|
|
|
fun onMessage(
|
|
ws: WebSocket,
|
|
event: Event
|
|
) {
|
|
if (event is MessageEvent) {
|
|
val data = event.data
|
|
|
|
if (data is String) {
|
|
console.log("Received message: $data")
|
|
if (data.startsWith("LOAD")) {
|
|
val patchJson = data.substring(5)
|
|
val patch = JSON.parse<PatchDTO>(patchJson)
|
|
|
|
Midi.setInput(patch.midiId, patch.midiName)
|
|
VstStringWorklet.load(patch)
|
|
MainView.requestUpdate()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fun onClose(
|
|
ws: WebSocket,
|
|
event: Event
|
|
): dynamic {
|
|
websocket = null
|
|
|
|
return "dynamic"
|
|
}
|
|
|
|
fun onError(
|
|
ws: WebSocket,
|
|
event: Event
|
|
): dynamic {
|
|
console.log("Error websocket!", ws, event)
|
|
|
|
websocket = null
|
|
|
|
return "dynamic"
|
|
}
|
|
|
|
fun send(message: String) {
|
|
websocket?.send(message)
|
|
}
|
|
} |