{{announcement.body}}
{{announcement.title}}

Analytics Web Socket

DZone 's Guide to

Analytics Web Socket

In this article, we discuss how to utilize a WebSocket to track a user's actions on a web page in Java.

· Java Zone ·
Free Resource

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. 

Java
 




xxxxxxxxxx
1
14


 
1
@Configuration
2
@EnableWebSocket
3
public class WebSocketConfiguration implements WebSocketConfigurer {
4
 
          
5
    @Bean
6
    public WebSocketHandler getAnalyticsHandler() { return new AnalyticsHandler(); }
7
 
          
8
    @Override
9
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
10
        //analytics web socket handler endpoint
11
        registry.addHandler(getAnalyticsHandler(), "/analytics-endpoint");
12
    }
13
 
          
14
}



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.

Java
 




xxxxxxxxxx
1
38


 
1
import org.springframework.web.socket.WebSocketSession;
2
import org.springframework.web.socket.handler.TextWebSocketHandler;
3
4
import java.util.ArrayList;
5
6
public class AnalyticsHandler extends TextWebSocketHandler {
7
8
    private  ArrayList<TextMessage> messages = new ArrayList<>();
9
    @Override
10
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
11
        // The WebSocket has been closed
12
        System.out.println("analytics web socket has been closed");
13
    }
14
15
    @Override
16
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
17
        // The WebSocket has been opened
18
        System.out.println("analytics web socket connection established");
19
        session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
20
21
    }
22
23
    @Override
24
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
25
        // A message has been received
26
        System.out.println("Analytics Message received: " + textMessage.getPayload());
27
        if (textMessage.getPayload().equals("get the mouse movement")) {
28
            String concatenatedString = "";
29
            System.out.println("messages size" + messages.size());
30
            for (TextMessage msg: messages) {
31
                System.out.println("concatenate.."+msg.getPayload());
32
                concatenatedString += "|" + msg.getPayload();
33
            }
34
            session.sendMessage(new TextMessage(concatenatedString));
35
        } else {
36
            messages.add(textMessage);
37
        }
38
    }



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.

JavaScript
 




xxxxxxxxxx
1
16


 
1
  <script>
2
   var socket = new WebSocket('ws://' + window.location.host + '/analytics-endpoint');
3
 
          
4
   // Add an event listener for when a connection is open
5
   socket.onopen = function() {
6
     console.log('Analytics WebSocket connection opened. Ready to send events.');
7
   };
8
 
          
9
   $("*").mousemove(function(values) {
10
       new_x = (event.pageX / screen.width);
11
       new_y = (event.pageY / screen.height);
12
       console.log(new_x, new_y);
13
       socket.send(new_x + "," + new_y);
14
       $("#cursor_hand").css({ left: new_x, top: new_y });
15
   });
16
 </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.  

JavaScript
 




xxxxxxxxxx
1
26


 
1
<script>
2
    var socket = new WebSocket('ws://' + window.location.host + '/analytics-endpoint');
3
    // Add an event listener for when a connection is open
4
    socket.onopen = function() {
5
      console.log('Analytics WebSocket connection opened. Ready to send events.');
6
    };
7
 
          
8
    // Add an event listener for when a message is received from the server
9
    socket.onmessage = function(message) {
10
      console.log('Message received from server: ');
11
      console.log(message);
12
      let positions = message.data.split("|");
13
      let cnt = 0;
14
      setInterval(function() {
15
        let points = positions[cnt++].split(",");
16
        console.log(points);
17
        points[0] = points[0] * 1000;
18
        points[1] = points[1] * 1000;
19
        $("#cursor_hand").css({ left: points[0], top: points[1] });
20
      }, 100);
21
    };
22
    function getAndPlayCursor() {
23
        console.log("get and play cursor");
24
        socket.send('get the mouse movement');
25
    }
26
</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.

https://youtu.be/8bPhAanARdA.


The source code is available on my GitHub.

Topics:
analytics ,java ,javascript ,springboot ,websocket ,websocket api

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}