Code Monkey home page Code Monkey logo

spring-websocket-angular6's Introduction

Spring WebSocket Angular6

The purpose of this project is to present a full example of notification/messaging service between an angular6 client and a spring application. There are many examples of clients using SockJS but with javascript directly and not angular (Examples).

This project is based on ng2-stompjs (Please consult its great documentation). But it aim to provide a complete and minimalist project to serve as plug'n'play project for both frontend and backend.

Usage

  1. Clone the repository git clone https://github.com/batiwo/spring-websocket-angular6.git
  2. Build the angular-websocket project with npm install to install dependencies and then ng build -base-href=.
  3. Build the spring-websocket project with mvn install
  4. Run the produced JAR spring-websocket-1.0-SNAPSHOT.jar with java -jar spring-websocket-1.0-SNAPSHOT.jar
  5. Go to http://localhost:8080/index.html and enjoy.

Screenshot of running demo

How to

Spring Server

The spring server is a basic spring-boot api with the spring-websocket dependency.

A Simple Configuration

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

The WebSocketConfiguration is also minimalist. We just configure the MessageBroker with an Endpoint and setAllowedOrigins to anyone. The Endpoint "/socket" means that you will connect to the ws://server-url/socket with your clients.

@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/socket").setAllowedOrigins("*");
    }
}

Notice that we do not use withSockJS()

registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();

A Simple Controller

A method that is called when a message is sent from the client (angular) to the server (spring)

@MessageMapping(RECEIVING_URL)
public void onReceivedMessage(String message) {
    System.out.println("New message received : " + message);
}

A method called each 1000ms that send a string message

@Scheduled(fixedRate = 1000)
public void sendMessage() {
    template.convertAndSend(SENDING_URL, buildNextMessage());
}

An optional but interesting method that send a message just after the client subscribed (or re-subscribed)

@SubscribeMapping(SENDING_URL)
public String onSubscribe() {
    return "SUBSCRIBED : " + message;
}

Angular Client

Step to re-create the angular client :

Prerequisites
  1. Create a new angular application ng new angular-websocket
  2. Install required dependencies npm install @stomp/ng2-stompjs and npm install rxjs-compat
  3. Create a service ng g service services/messaging
  4. Then develop the application code.
Sample explanation

Here is some useful import

import { StompService, StompConfig, StompState } from "@stomp/ng2-stompjs";
import { Message } from "@stomp/stompjs";
import { Observable, BehaviorSubject } from "rxjs";

Create Stomp Configuration

let stompConfig: StompConfig = {
  url: socketUrl,
  headers: {
    login: "",
    passcode: ""
  },
  heartbeat_in: 0,
  heartbeat_out: 20000,
  reconnect_delay: 5000,
  debug: true
};

Create Stomp Service

this.stompService = new StompService(stompConfig);

Connect to a Stream

this.stompService.subscribe(streamUrl);

Send a message from client (angular) to the server (spring)

this.stompService.publish(url, JSON.stringify(message));

Monitor the state this.stompService.state

Contributor

Sébastien DRUJONT

spring-websocket-angular6's People

Contributors

batiwo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.