我正在用http4k websocket构建一个小型的websocket应用程序,看起来没有关于如何用它实现消息广播的文档(也就是说,除了发送消息的客户端之外,对发送消息的所有客户端做出反应)。有可能吗?
发布于 2019-05-01 07:50:00
如果问题是“http4k是否附带了整个分布式消息传递平台”,那么答案是否定的。但是,如果您只希望有一个消息传递节点来跟踪内存中的所有消息和连接的websockets,那么这样做非常简单。
此代码来自于一个http4k演示项目,它实现了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)
)
}https://stackoverflow.com/questions/55925439
复制相似问题