Generate realtime charts using Vert.x websocket and highchart.js
Objectif: Update chart data on the client side as events occurs on the business side.
Update: It’s the second time that DZone.com promote my links, thank you, it really encourage myself to write better articles.
Tools:
- Vert.x, the java equivalent to node.js
- Hightcharts.js a advanced javascript charting library.
- WebSocket is a full duplex protocol used to connect the browser to the server. ws for brevity.
Result:

Structure: Highcharts directory contains
- jquery-1.7.2.js
- highcharts.js
- charts.html
- WebSocketsServer.groovy
Command: after having installed Vert.x on at the same level of the directory use the command vertx run highcharts/WebSocketsServer.groovy then point your browser to localhost:8080.
How it works: When the page is loaded the first time it establish a websocket connection with the server, the connection is not closed until you close the tab of the browser. When you click on the draw button, you’re actually sending a event to the server which in counterpart is sending a json response through the ws channel. Javascript parse the location of the new point and update the chart.
Charts.html
<html>
<head><title>Web Socket Test</title></head>
<script src="jquery.js" type="text/javascript"></script>
<script src="highcharts.js" type="text/javascript"></script>
<body>
<script>
var dataseries;
var socket;
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8080/myapp");
socket.onmessage = function(event) {
//alert('data'+event.data)
var point = JSON.parse(event.data);
//alert('json ok'+point)
var npoint = [parseInt(point.x),parseInt(point.y)];
dataseries.addPoint(npoint);
}
} else {
alert("Your browser does not support Websockets. (Use Chrome)");
}
function send(message) {
if (!window.WebSocket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("The socket is not open.");
}
}
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
backgroundColor: {
linearGradient: [0, 0, 0, 400],
stops: [
[0, 'rgb(250, 180, 180)'],
[1, 'rgb(255, 240, 240)']
]
},
renderTo: 'container',
type: 'scatter',
margin: [70, 50, 60, 80],
events: {
load: function(e) {
dataseries = this.series[0];
}
}
},
title: {
text: 'User supplied Love'
},
subtitle: {
text: 'Because we all love our Moms'
},
xAxis: {
minPadding: 0.2,
maxPadding: 0.2,
maxZoom: 60
},
yAxis: {
title: {
text: 'Value'
},
minPadding: 0.2,
maxPadding: 0.2,
maxZoom: 60,
plotLines: [{
value: 0,
width: 1,
color: '#FF0000'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
line: {
dataLabels: {
color: '#CCC'
},
marker: {
lineColor: '#333'
}
},
series: {
lineWidth: 2,
color: '#FF0000',
point: {
events: {
'click': function() {
if (this.series.data.length > 1) this.remove();
}
}
}
}
},
series: [{
data: [[0, 0]]
}]
});
});
});
</script>
<form onsubmit="return false;">
<input type="hidden" name="message" value='draw'/>
<input type="button" value="Draw" onclick="send(this.form.message.value)"/>
</form>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
WebSocketServer.groovy
package websockets
def halfpart = []
halfpart.add([-2,25])
halfpart.add([-3,35])
halfpart.add([-4,45])
halfpart.add([-6,55])
halfpart.add([-7,65])
halfpart.add([-7,80])
halfpart.add([-6,90])
halfpart.add([-5,97])
halfpart.add([-4,100])
halfpart.add([-3,97])
halfpart.add([-2,90])
halfpart.add([-1,82])
halfpart.add([-0,75])
def drawing = []
halfpart.each{ drawing << it }
drawing.pop()
halfpart.reverse().each{ drawing << [-it[0],it[1]] }
drawing << [0,0]
println(drawing)
def counter = 0
vertx.createHttpServer().websocketHandler { ws ->
ws.dataHandler { data ->
def location = drawing[counter%drawing.size()]
def template = """{"x":"${location[0]}","y":"${location[1]}"}"""
ws.writeTextFrame(template)
counter++
}
}.requestHandler { req ->
if (req.uri == "/") req.response.sendFile "highcharts/charts.html"
if (req.uri == '/jquery.js') req.response.sendFile('highcharts/jquery-1.7.2.js')
if (req.uri == '/highcharts.js') req.response.sendFile('highcharts/highcharts.js')
}.listen(8080)


