Can someone point me to kotlin browser side websoc...
# javascript
l
Can someone point me to kotlin browser side websockets? Google searching turns up lots of server side code and tutorials which use regular javascript on the browser side. I am finding it extremely challenging to find information about kotlin js, in fact I don't even know if that is a thing. I am using the html DSL in a create-kotlin-react project. Maybe I came to this party too late. Need a break through.
BTW, I got REST calls working. Now I want to switch the app over to ws to make a multi user thing work.
c
I’ve used websockets by adapting the Ktor sample client from JS to Kotlin using the standard browser Websocket API https://github.com/ktorio/ktor-samples/blob/master/app/chat/resources/web/main.js
Copy code
fun main() {
    connect()
}

fun connect() {
    // First we create the socket.
    // The socket will be connected automatically asap. Not now but after returning to the event loop,
    // so we can register handlers safely before the connection is performed.
    console.log("Begin connect")
    if (window.location.protocol == "https:") {
        socket = WebSocket("wss://" + window.location.host + "/ws")
    } else {
        socket = WebSocket("ws://" + window.location.host + "/ws")
    }

    // We set a handler that will be executed if the socket has any kind of unexpected error.
    // Since this is a just sample, we only report it at the console instead of making more complex things.
    socket!!.onerror = {

    }

    // We set a handler upon connection.
    // What this does is to put a text in the messages container notifying about this event.
    socket!!.onopen = {

    }

    // If the connection was closed gracefully (either normally or with a reason from the server),
    // we have this handler to notify to the user via the messages container.
    // Also we will retry a connection after 5 seconds.
    socket!!.onclose = { ev ->
        val evt = ev.asDynamic()
        // Try to gather an explanation about why this was closed.
        var explanation = ""
        if (evt.reason && evt.reason.length > 0) {
            explanation = "reason: " + evt.reason
        } else {
            explanation = "without a reason specified"
        }

        // Notify the user using the messages container.
        handleTextMessage("info", "Disconnected with close code " + evt.code + " and " + explanation)
        // Try to reconnect after 5 seconds.
        window.setTimeout({ connect() }, 5000)
    }

    // If we receive a message from the server, we want to handle it.
    socket!!.onmessage = { ev ->

    }
}
l
thank you, I will give this a try tonight after work.
l
@Robert Jaros What is the javascript bit at the top?
Actually, the confusing part is the "Inside Javascript"
r
I don't know, I'm not the author 🙂
But I'm using this websocket implementation in KVision, and it works quite well :-)
👍 1