An aspiring software craftsman journey
Server-Sent Events (aka SSE) are part of HTML5 and allow a web page to get updates from a server. It is a one way messaging form server to clients in contrast to Web Sockets where communication is bidirectional.
In this post, I will create a monitoring dashboard that shows JVM stats of a running Tomcat server. Off we go!
In the server side, no need for more than a vanilla servlet that pushes JVM stats every second to its clients. Let’s see how to do that:
Most of the code is self explanatory, the servlet gathers JVM memory stats from the
Runtime class and creates a JSON object with current values of total, max and free memory.
The devil is in the details. Here are the two important tricks:
The response content type should be set to
The sent event must be of the following form :
data: my_data \n\n
For more details about SSE event types, please refer to the W3C SSE specification.
This servlet will be deployed in the Tomcat instance to monitor and will serve the
/health URL. That’s all for the server side, easy .
Mainly, the client side will receive events asynchronously from the server (using the EventSource object).
Whenever it receives a message, it will execute the
onmessage function which will update the graph with new data. That’s all on the client side, easy too .
The complete source code and running instructions are available on GitHub here.
If you run the server and browse
http://localhost:8080/dashboard.html , you will see the server’s health graph being updated every second automatically. Here is a screenshot:
This example is about monitoring the server’s memory. We can imagine any sort of stats such as the number of active http sessions, the number of http requests/second, etc.
Before leaving this page, if you have already used SSE for other use cases, do not hesitate to share your experience in comments.
Credit: the plot graphic uses the excellent flot charts library.