DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Apache Spark 4.0: Transforming Big Data Analytics to the Next Level
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API
  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview

Trending

  • Monoliths, REST, and Spring Boot Sidecars: A Real Modernization Playbook
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  1. DZone
  2. Data Engineering
  3. Data
  4. Analytics Web Socket

Analytics Web Socket

By 
Nagappan Subramanian user avatar
Nagappan Subramanian
DZone Core CORE ·
Apr. 10, 20 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
8.6K Views

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. 

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.

Analytics WebSocket

Opinions expressed by DZone contributors are their own.

Related

  • Apache Spark 4.0: Transforming Big Data Analytics to the Next Level
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API
  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!