I’m implementing a server based on Kotlin and Ktor. The goal is to send a gcode file which the receiver, a raspberry pi 1B, shall transmit to my ender 3 printer. To see the current state I used WebSockets at first. This went really well but to be honest I don’t need the overhead which comes with WebSockets because I only want to send states to whomever listen. So, the next possibility was Server Sent Events.
Server Sent Events are available for years now but not really present in people minds, so in my. However, there are a few tutorials and references to that and it was not hard to implement such events beside of one thing: Custom Message IDs.
The most tutorials to such scenarios propagate that you can pick whatever Identifier you want and just add a message listener for that. But that doesn’t work as easy as it sounds. Maybe, there is a way by implementing an own EventSource class but for that I am not experienced with JavaScript.
Just to have a bit more context. The EventSource class is in highlevel responsible to create the connection and wrap the events to a MessageEvent. One can register to:
EventSource::onopen
EventSource::onclosed
EventSource::onmessage
EventTarget::addEventListener
Usually, one would take addEventListener and put in an identifier and a function, but as said before that doesn’t work. In a forum one said that all unknown identifier will be delegated into the onmessage channel.
However, regardless which message identifier I chose, it every time landed in onmessage.
To overcome this I wrapped my data class into another with the fields “Identifier” and “Data”. So, now I can use a switch case and every message gets processed by the correct function.
Would like to know that earlier, it took me 2 days of reading references and for the workaround 5 minutes.