Inform registered customers by utilizing AngularJS (angular-websocket-service) and Spring Boot to implement Websockets notifications

Exploring the world of AngularJS and FullStack development is an exciting journey for me. The architectural setup of my current app is already in place and ideally should not be altered (for security reasons). I've been able to send messages to the server using angular-websocket-service. Below is a snippet of the frontend service code:

proxiMiamApp.service('WebSocketService', function ($websocket) {
var wsEndpoint = {};

this.openWsEndpoint = function () {
    wsEndpoint = $websocket.connect("ws://localhost:9000/proximiamHandler");
    console.log(wsEndpoint);
    return wsEndpoint;
}

this.sendMessage = function(){
    if($.isEmptyObject(this.wsEndpoint)){
        this.openWsEndpoint();
    }

    eventUser = {

        idEvent : '1',
        idUser : '49'
    };

    wsEndpoint.register('/eventUser', function(){

        console.log('Register OK!');
    });
    console.log('Ready!');
    wsEndpoint.emit('/eventUser',eventUser);


}});

On the backend, I am utilizing an implementation of the WebSocketHandler interface:

@Controller
public class ProximiamHandler implements WebSocketHandler {

@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
    System.out.println("afterConntectionEstablished called");
}

@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

    System.out.println("handleMessage called");
    // My code here...

}

@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
    System.out.println("handleTransportError called");
}

@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
    System.out.println("afterConnectionClosed called");
}

@Override
public boolean supportsPartialMessages() {
    return true;
}}

The WebSocketHandler implementation is invoked through Spring's WebSocketConfigurer

@Configuration
@EnableWebSocket
@Controller
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(myHandler(), "/proximiamHandler").setAllowedOrigins("*");
}

@Bean
public WebSocketHandler myHandler() {
    return new ProximiamHandler();
}}

I have a few questions:

  1. Is it possible to notify subscribed clients with this architecture?
  2. If so, what is the process for doing so?
  3. Can the server respond to subscribed clients with an Object or String?

Thank you in advance for your guidance.

Answer №1

Is it possible to send notifications to subscribed clients using this setup? => Affirmative.

If so, how can I go about it? => Utilize the Spring web socket APIs by preserving the 'WebSocketSession' provided to you through the "afterConnectionEstablished" callback. Use the sendMessage() function of the Web socket session to dispatch notifications to the client.

Can the server send any data back to the subscribed clients? (like an Object or a String) => You have the option to format your data in either JSON or XML and encapsulate it with "WebSocketMessage" before sending it to the client.

I don't have experience with Spring, but I'm sharing these insights based on my familiarity with web sockets. I hope this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing and comparing category IDs in JavaScript to effectively store and render subcategories

My goal is to set the current category ID in a variable, and if the category changes, I want to store that as well. Then, I need to compare both IDs. If they are not equal, I want to set the subcategory to null. However, I am unsure of where my mistake lie ...

The array data is not being shown on the view as expected when utilizing $scope

I am struggling with the code snippet below in my view: myapp.controller('AddChoreController', ['$scope', function ($scope) { var choreList = this; $scope.choreList.chore = [{ name: 'Gun Running', frequency: &ap ...

The dimensions on Next.js pages exceed those of the viewport by a significant margin

I have recently encountered a perplexing issue where the dimensions of my webpage appear to be 2.7 times larger than the viewport, even when there is no content or styles applied. The strange part is that it seems as though the page has been scaled up, eve ...

Guide to incorporating WebElement scrolling in Selenium using Java?

I need to implement a scroll function for a table on my webpage rather than scrolling the entire page, so using window.scrollBy is not an option. After attempting to find the container responsible for the scroll functionality in the DOM (with no luck), I ...

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

Ways to access a particular property of a child component object from the parent component

Is there a way to access a child component's "meta" property from the parent component without using the emit method? I am aware of the solution involving an emit method, but I'm curious if there is a simpler approach to achieving this. // Defau ...

Utilizing JavaScript Files Instead of NPM as a Library for Open Layers: A Step-by-Step Guide

I've been attempting to get Open Layers to function in my Eclipse web development environment, but I've encountered some challenges along the way. The setup instructions provided on the Open Layers website focus mainly on using npm. Nevertheless, ...

Running a Mongoimport command within a JavaScript/Node.js script

Is there a node.js/javascript library available that allows for the use of mongoimport within code? From what I understand, mongoimport is similar to an .exe file that needs to be executed before being able to utilize its text input environment. Is it fe ...

Routing static pages in Angular 2

I successfully created a static page using Angular 2. When I run ng serve and visit my page, it functions as intended. Specifically, I can navigate to a specific page by typing in the URL, such as www.mysite.com/resume. However, after uploading it to my si ...

Managing the layout with React Native Flexbox to evenly distribute items

Check out this React Native Demo I put together featuring Santa images being added and removed in a Flexbox. Bunch of Santas I noticed that when there are more than 3 Santas, the layout shifts to the left. I'm curious about how to keep the Santas ce ...

Animating CSS Pixel Fragments

After applying a simple CSS animation that moves size and box shadows from one side of the screen to the other, I am noticing residual pixel fragments left behind. To see this issue in action on Chrome 66, check out the Code Pen: Is there a way to remove ...

jade, express, as well as findings from mysql

My goal is to display the results of an SQL query in Jade, which pulls data from a table of banners. Each banner has a unique id and falls under one of three types. Here is my current code : express : connection.query("SELECT * FROM banner_idx ORDER BY ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

Determining the Existence of Duplicates in an HTML Table with Multiple Inputs Using JavaScript

After spending countless hours on research with no luck, I've finally come to seek assistance from you. In my form, I have an input field and a select field, along with a table generated using PHP from my database that displays team names and their r ...

Creating Tree diagrams with pie charts using D3

Has anyone tried creating a D3 pie component within each node of a tree? I've managed to build the tree and a single pie separately, but I'm struggling to combine them. My JSON data looks like this: window.json = { "health": [{ "value" ...

Whenever I try to run npm start, my webpack is not able to locate my index.html page

Recently delving into the world of node.js and its packages, I initiated by executing npm init to lay out the package.json structure shown below: { "name": "test", "version": "1.0.0", "description": & ...

Maximize the sum of diverse numbers effectively

I have an array that contains objects structured like this: [ { "id": 91, "factor": 2, "title": "Test Product", "price": 50, "interval": 1, "setup": 0, "optional": false }, { "id": 92, "factor": 1, "title": "A ...

What is the best way to link this to a function in AngularIO's Observable::subscribe method?

Many examples use the Observable.subscribe() function in AngularIO. However, I have only seen anonymous functions being used like this: bar().subscribe(data => this.data = data, ...); When I try to use a function from the same class like this: update ...

What is the solution to fixing the JSON parsing error that says 'JSON.parse: bad control character in string literal'?

When sending data from NodeJS Backend to the client, I utilize the following code: res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) )) //No errors occur here and the object is successfully stri ...

what's the reason for ajax constantly sending requests back-to-back?

Today, I find myself pondering. In my current project, the ajax calls are not behaving asynchronously. Each request is being sent one after the other. As one request is being processed, all other requests are getting stuck in a pending state. You can ob ...