Reputation: 1403
I'm building a small websocket app with http4k websocket and looks like there is no documentation about how to implement message broadcasting with it (i.e. react to a message sending it to all the clients except the one that sent the message). Is it possible?
Upvotes: 0
Views: 327
Reputation: 264
If the question is "does http4k ship with an entire distributed messaging platform", then the answer is no :) . However, if you just want to have a single messaging node which keeps track of all of the messages and connected websockets in memory, then it's quite simple to do.
This code is adapted from an http4k demo project which implements a chat server in 30 lines of Kotlin:
fun IrcApp(): PolyHandler {
val userCounter = AtomicInteger()
val participants = ConcurrentHashMap<String, Websocket>()
fun newConnection(ws: Websocket) {
val id = "user${userCounter.incrementAndGet()}"
participants += id to ws
ws.onMessage { new ->
participants.values
.filterNot { it == ws }
.forEach { it.send(WsMessage("$id: ${new.bodyString()}")) }
}
ws.onClose {
participants -= id
}
}
return PolyHandler(
static(ResourceLoader.Classpath()),
websockets("/ws" bind ::newConnection)
)
}
Upvotes: 1