Francis Mariano
03/11/2023, 10:24 PMBig Chungus
03/11/2023, 10:26 PMBig Chungus
03/11/2023, 10:26 PMFrancis Mariano
03/11/2023, 10:44 PMrouting {
webSocket("/echo") {
send("Please enter your name")
for (frame in incoming) {
frame as? Frame.Text ?: continue
val receivedText = frame.readText()
if (receivedText.equals("bye", ignoreCase = true)) {
close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE"))
} else {
send(Frame.Text("Hi, $receivedText!"))
}
}
}
}
When my post endpoint receives a message I would like to send that message for the client established in websocket connection.
route("api/host") {
post("") {
val host = call.receive<HostDto>()
// send host via websocket
}
}
I do not know how to do that. Anyone have some any idea, please???Casey Brooks
03/11/2023, 10:58 PMChannel
to send data from the HTTP call to an active Websocket connection, but this is not advisable in any kind of real-world scenario, since in production your HTTP calls and websockets might be routed to different server processes. For real-world applications, you’d probably want to use something like Redis to communicate between HTTP calls and websockets
// this channel is a singleton
val channel = Channel<HostDto>()
routing {
webSocket("/echo") {
launch {
for(hostDto in channel) {
send(hostDto.toString())
}
}
send("Please enter your name")
for (frame in incoming) {
frame as? Frame.Text ?: continue
val receivedText = frame.readText()
if (receivedText.equals("bye", ignoreCase = true)) {
close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE"))
} else {
send(Frame.Text("Hi, $receivedText!"))
}
}
}
}
route("api/host") {
post("") {
val host = call.receive<HostDto>()
channel.send(host)
}
}
Francis Mariano
03/11/2023, 11:12 PMAdel Ayman
03/12/2023, 1:02 AM