Spring Boot + Websocket + Example

By Dhiraj Ray, 28 January,2017   | Last updated on: 11 March,2017

Hello friends, let us again walk through creating websocket connection in java but this time with spring and STOMP protocol.We will also make use of Spring security to restrict websocket server reply to a particular client instead of broadcasting to all clients.Here, We will be using spring boot features and all configurations will be completely based on java config(no xml). Though, this post will be spring websocket connection with STOMP and spring security,here is my previous post that describes spring websocket connection without STOMP

What is STOMP

STOMP stands for Streaming Text Oriented Messaging Protocol. As per wiki, STOMP is a simple text-based protocol, designed for working with message-oriented middleware (MOM). It provides an interoperable wire format that allows STOMP clients to talk with any message broker supporting the protocol.

Environment Setup

1. JDK 8 2. Spring Boot 3. Intellij Idea/ eclipse 4. Tomcat(embedded with Spring) 5. Maven

Maven Dependencies

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> </parent> <properties> <tomcat.version>8.0.3</tomcat.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </dependencies>

Spring Bean Configuration

First of all let us configure our STOMP message broker.In WebSocketConfig.java we have defined our message broker STOMP endpoint and websocket application endpoint.

@Configuration : It indicates that it is a Spring configuration class.

@EnableWebSocketMessageBroker : It enables WebSocket message handling, backed by a message broker. Here we are using STOMP as a mesage broker.

The method enableSimpleBroker() enables a simple memory-based message broker to carry the messages back to the client on destinations prefixed with "/topic". It also designates the "/app" prefix for messages that are bound for @MessageMapping-annotated methods in controller class. This prefix will be used to define all the message mappings; for example, "/app/message" is the endpoint that the WebSocketController.processMessageFromClient() method is mapped to handle.

package com.devglan; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic/", "/queue/"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/greeting");; } }

Now let us define our controller and map the websocket connection endpoint.

@MessageMapping: This isto map the message headed for the url /message

@SendToUser: indicates that the return value of a message-handling method should be sent as a org.springframework.messaging.Message to the specified destination(s) prepended with "/user/{username}" where the user name is extracted from the headers of the input message being handled.

@MessageExceptionHandler: throw any exceptions caused by STOMP to the end user on the /queue/errors destination.

@Payload: to extract the payload of a message and optionally convert it using spring MessageConverter.

package com.devglan.controller; import java.security.Principal; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageExceptionHandler; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.messaging.simp.annotation.SendToUser; import org.springframework.stereotype.Controller; import com.google.gson.Gson; @Controller public class WebSocketController { @Autowired private SimpMessageSendingOperations messagingTemplate; @MessageMapping("/message") @SendToUser("/queue/reply") public String processMessageFromClient(@Payload String message, Principal principal) throws Exception { String name = new Gson().fromJson(message, Map.class).get("name").toString(); //messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/reply", name); return name; } @MessageExceptionHandler @SendToUser("/queue/errors") public String handleException(Throwable exception) { return exception.getMessage(); } }

We wll be using spring boot feature to run our application. The spring boot maven plugin will collect all the jars on the classpath and builds a single, runnable jar file, which makes it more convenient to execute and transport our service. It searches for the public static void main() method to flag as a runnable class and provides built-in dependency resolver that sets the version number to match spring boot dependencies.

SpringBootServletInitializer enables process used in Servlet 3.0 using web.xml

@SpringBootApplication: This is a convenience annotation that is equivalent to declaring @Configuration,@EnableAutoConfiguration and @ComponentScan.

package com.devglan.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication public class Application extends SpringBootServletInitializer { private static Class applicationClass = Application.class; public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

client side


The connect() will create a web socket connection. Remember the mapping we did in WebSocketConfig.java class for /greeting.

The function onmessage() will execute itself once any message is broadcasted by server

function showGreeting() will be simply showing the message received by the server broadcast.

send() function will construct a JSON message and sends message to the server.

function connect() { var socket = new WebSocket('ws://localhost:8080/greeting'); ws = Stomp.over(socket); ws.connect({}, function(frame) { ws.subscribe("/user/queue/errors", function(message) { alert("Error " + message.body); }); ws.subscribe("/user/queue/reply", function(message) { showGreeting(message.body); }); }, function(error) { alert("STOMP error " + error); }); } function disconnect() { if (ws != null) { ws.close(); } setConnected(false); console.log("Disconnected"); } function sendName() { ws.send($("#name").val()); } function showGreeting(message) { $("#greetings").append(" " + message + ""); }

Run Application

1. Run the Application.java as a java application. 2. Open the browser and hit the URL - http:localhost:8080. It will prompt for username and password as below.By default the username is user and password you can check in the console. spring-boot-websocket-security-login 3. Now, you can see the index.html after successful authentication. 4. Click on connect button to make the socket connection. 5. Enter the name and post the message and you can see the greeting message as below from websocket server.



I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download the source


Spring Websocket Reference

STOMP wiki

Spring Boot References

Suggest more topics in suggestion section or write your own article and share with your colleagues.

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.

Further Reading: