Analytics Web Socket
Join the DZone community and get the full member experience.
Join For FreeWeb analytics is the measurement and collection of continuous activity of web usage. This requires continuous communication between client and server. To do that, having a REST API adds an overhead of connection and TLS handshakes every communication. Also, each user event requires communications and a few microseconds worth of a response to report it to the backend.
For this kind of scenario, WebSockets come to the rescue. A WebSockets is a full-duplex communication, which makes a connection once and then sends/receives data throughout the persisted connection. For more on WebSockets, check out this article.
In this article, we will track a user's mouse movement throughout a web page. Real-time tracking of user mouse movement will be relayed through the persistent WebSocket. Now, when we open the analytics page, it will record the user's cursor movement on the page.
We are using Spring Boot 2.2.5.RELEASE, webstarter, and a WebSocket package.
Create a WebSocket Endpoint
Websocketconfigurer
is used to create the WebSockets endpoints with the handler mappings.
xxxxxxxxxx
public class WebSocketConfiguration implements WebSocketConfigurer {
public WebSocketHandler getAnalyticsHandler() { return new AnalyticsHandler(); }
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//analytics web socket handler endpoint
registry.addHandler(getAnalyticsHandler(), "/analytics-endpoint");
}
}
Mouse movements are recorded with positions as a string, so the handler can be a text handler. Let's extend TextWebSocketHandler
, which will work with the listeners while the connection is established.
xxxxxxxxxx
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.ArrayList;
public class AnalyticsHandler extends TextWebSocketHandler {
private ArrayList<TextMessage> messages = new ArrayList<>();
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// The WebSocket has been closed
System.out.println("analytics web socket has been closed");
}
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// The WebSocket has been opened
System.out.println("analytics web socket connection established");
session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
}
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
// A message has been received
System.out.println("Analytics Message received: " + textMessage.getPayload());
if (textMessage.getPayload().equals("get the mouse movement")) {
String concatenatedString = "";
System.out.println("messages size" + messages.size());
for (TextMessage msg: messages) {
System.out.println("concatenate.."+msg.getPayload());
concatenatedString += "|" + msg.getPayload();
}
session.sendMessage(new TextMessage(concatenatedString));
} else {
messages.add(textMessage);
}
}
Now, the text message payload sent will be checked for getting or saving mouse movement. Then, it will return the previously provided list of mouse points.
In the frontend, we will create two pages, one of which will be for the user to navigate the company dashboard page, where user mouse movements will be recorded and relayed to the backend. The mouse move listener will be invoked for each mouse movement. Each movement will be relayed through the WebSocket.
xxxxxxxxxx
<script>
var socket = new WebSocket('ws://' + window.location.host + '/analytics-endpoint');
// Add an event listener for when a connection is open
socket.onopen = function() {
console.log('Analytics WebSocket connection opened. Ready to send events.');
};
$("*").mousemove(function(values) {
new_x = (event.pageX / screen.width);
new_y = (event.pageY / screen.height);
console.log(new_x, new_y);
socket.send(new_x + "," + new_y);
$("#cursor_hand").css({ left: new_x, top: new_y });
});
</script>
The second page will open the analytics WebSocket and request to get the mouse movements on the click of the play button. It will send all the travel mouse positions to the client WebSocket. At each interval, for 100 ms, it will position the cursor icon to indicate the user movements.
xxxxxxxxxx
<script>
var socket = new WebSocket('ws://' + window.location.host + '/analytics-endpoint');
// Add an event listener for when a connection is open
socket.onopen = function() {
console.log('Analytics WebSocket connection opened. Ready to send events.');
};
// Add an event listener for when a message is received from the server
socket.onmessage = function(message) {
console.log('Message received from server: ');
console.log(message);
let positions = message.data.split("|");
let cnt = 0;
setInterval(function() {
let points = positions[cnt++].split(",");
console.log(points);
points[0] = points[0] * 1000;
points[1] = points[1] * 1000;
$("#cursor_hand").css({ left: points[0], top: points[1] });
}, 100);
};
function getAndPlayCursor() {
console.log("get and play cursor");
socket.send('get the mouse movement');
}
</script>
The following video will show the user's mouse movements on the dashboard page and the page to show the tracked mouse movements on the analytics view page. This will be followed by a walk-through of the code.
The source code is available on my GitHub.
Opinions expressed by DZone contributors are their own.
Comments