# ktor

Janez Kolar

11/19/2020, 8:21 AM
Hi! I would like to create webserver to send data to frontend via websocket. I found example (below) how to make list of connections and sync data to all. Is there some more efficient way to do this? Something like multicast? Can someone tell me how many clients is possible to connect to such websocket? In real case I need to sync position of 100 cars to 10000 clients every second... What would be the best way with ktor?
Copy code
routing {
    val wsConnections = Collections.synchronizedSet(LinkedHashSet<DefaultWebSocketSession>())

    webSocket("/chat") { // this: DefaultWebSocketSession
        wsConnections += this
        try {
            while (true) {
                val frame = incoming.receive()
                when (frame) {
                    is Frame.Text -> {
                        val text = frame.readText()
                        // Iterate over all the connections
                        for (conn in wsConnections) {
        } finally {
            wsConnections -= this


11/19/2020, 7:38 PM
Disclaimer: not an expert Definitely interesting as this looks very similar to something my team has thought of as well The issue here is sort of two-fold: 1. How do you push data to the client 2. How do you solve the scalability of your solution To answer 1, websockets would work but there’s also an alternative that allows you to be more flexible. I think this video will do you good on how LinkedIn solved a problem similar to yours - and I’m assuming if a car’s position fails/drops out for a few seconds, it’s not a big deal - which you can find @

They don’t use ktor but I’m hoping what they do with Play+Akka can be done with ktor too. As to how many websockets can connect - you will have to test this out. The more powerful a machine is, the more connections it can handle. I’m sure you can architect something that scales horizontally by simply adding more machines. Hope this helps!
Seems like there’s an SSE example ready in ktor too!