我正在使用http4k websocket构建一个小的websocket应用程序,看起来没有关于如何使用它实现消息广播的文档(即对发送给除发送消息的客户端之外的所有客户端的消息做出反应)。可能吗?
如果问题是“http4k是否附带整个分布式消息传递平台”,那么答案是否定的:)。但是,如果您只想拥有一个消息节点来跟踪内存中的所有消息和连接的websockets,那么这很简单。
此代码改编自http4k demo project,它实现了30行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)
)
}