Skip to content

Instantly share code, notes, and snippets.

@eoinahern
Last active October 21, 2021 17:49
Show Gist options
  • Save eoinahern/d8d1b26b501b3c54791e5d32b647a8b1 to your computer and use it in GitHub Desktop.
Save eoinahern/d8d1b26b501b3c54791e5d32b647a8b1 to your computer and use it in GitHub Desktop.
connecting to ktor websocket endpoints with simple node.js client (dont really use node a lot)
const WebSocket = require('ws')
//setup input from console
var stdin_input = process.stdin;
stdin_input.setEncoding("utf-8");
//connect socket!!
const url = "ws://localhost:8080/output_all";
const connection = new WebSocket(url);
//console message!!
console.log("enter message");
//send message to socket server!!
stdin_input.on("data", function(data){
connection.send(data)
});
//listen to message from socket server!!!
connection.onmessage = (frame) => {
console.log(frame.data)
}
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
val wsConnections = Collections.synchronizedSet(LinkedHashSet<DefaultWebSocketSession>())
install(WebSockets) {
}
routing {
webSocket("/chat") {
while (true) {
val frame = incoming.receive() // suspend
when (frame) {
is Frame.Text -> {
val text = frame.readText()
outgoing.send(Frame.Text(text)) // suspend
}
}
}
}
/**
* repeatedly send a random number between 0 and 100
* every 3 seconds
*/
webSocket("/repeat") {
while (true) {
delay(3000)
outgoing.send(Frame.Text(Random.nextInt(0, 100).toString()))
}
}
webSocket("output_all") {
wsConnections += this
try {
while (true) {
val frame = incoming.receive()
when (frame) {
is Frame.Text -> {
for (socket in wsConnections) {
val text = frame.readText()
socket.outgoing.send(Frame.Text(text))
}
}
}
}
} finally {
wsConnections -= this
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment