Analytics Web Socket
Join the DZone community and get the full member experience.Join For Free
Web 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.
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.
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.
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.
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.