Skip to content

Instantly share code, notes, and snippets.

@asad-awadia
Created March 2, 2021 03:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asad-awadia/014a2878e67e701b234b165526bf75ef to your computer and use it in GitHub Desktop.
Save asad-awadia/014a2878e67e701b234b165526bf75ef to your computer and use it in GitHub Desktop.
Vert.x live chat feeds
fun main() {
val rooms = mutableMapOf<String, MutableSet<ServerWebSocket>>()
val vertx = Vertx.vertx()
vertx.createHttpServer()
.webSocketHandler {
rooms.computeIfPresent(it.path()) { _, listOfConnections ->
listOfConnections.add(it)
listOfConnections
}
rooms.computeIfAbsent(it.path()) { _ -> mutableSetOf(it) }
it.closeHandler { _ -> rooms[it.path()]?.remove(it) }
it.textMessageHandler { event ->
rooms[it.path()]?.filterNot { ws -> ws == it }?.forEach { ws -> ws.writeTextMessage(event) }
}
}
.listen(9999)
.onSuccess { println("server successfully started on port 9999") }
.onFailure { println("failed to start server: " + it.stackTrace) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment