Skip to content

Quickstart

Ralph Schaer edited this page Jun 14, 2021 · 3 revisions

Here is a quick setup guide to start a wamp2spring application with Spring Boot.

Create a Spring Boot application either manually or with the Spring Intializr. Choose WebSocket as dependency.

Add the wamp2spring dependency to the project.

  <dependency>
    <groupId>ch.rasc</groupId>
    <artifactId>wamp2spring-servlet</artifactId>
    <version>2.0.4</version>
  </dependency>

Open the main application class and add the annotation @EnableServletWamp. The annotation configures all the necessary parts and creates a WAMP WebSocket endpoint listening on the url /wamp.

  @SpringBootApplication
  @EnableServletWamp
  public class Application {
    public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
    }
  }  

This setup is already sufficient to send and consume WAMP messages from a client. For this example I use the JavaScript library AutobahnJS but you can use any available WAMP library.

<script src="autobahn.min.js"></script>
<script>
const connection = new autobahn.Connection({url: 'ws://127.0.0.1:8080/wamp'});

connection.onopen = session => {
   session.subscribe('myapp.topic', args => {
     //handle event
   });

   //in another part of the application, publish an event
   session.publish('myapp.topic', ['Hello, world!']);

};

connection.open();
</script>

RPC: Calling methods in the application

You can annotate methods in a Spring managed bean with @WampProcedure and any WAMP client can call these methods.

@Service
public class MyService {
  @WampProcedure("add")
  public int add(int a, int b) {
    return a + b;
  }
const result = await session.call('add', [3,10]); // 13

Pub/Sub: Listening and publishing events from the application

Annotate methods with @WampListener to listen for events and inject the WampPublisher bean to publish messages to clients.

@Service
public class MyService {

	private final WampPublisher wampEventPublisher;

	public TestService(WampPublisher wampEventPublisher) {
		this.wampEventPublisher = wampEventPublisher;
	}

    @WampListener("myapp.topic")
    public void eventListener(String arg) {
        this.wampEventPublisher.publishToAll("myapp.servertopic", "payload");
    }
   session.subscribe('myapp.servertopic', args => {
     // "payload"
   });
   
   session.publish('myapp.topic', ['Hello, world!']);
Clone this wiki locally