Spring WebSocket simplifies the development of real-time, bidirectional communication between web browsers and servers. By leveraging WebSocket technology, you can build interactive applications like chat apps, real-time dashboards, or collaborative tools.
Setting up your Project
Gradle
implementation 'org.springframework.boot:spring-boot-starter-websocket'
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocket Configuration
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// Enable a simple memory-based message broker to carry messages back to the client on destinations prefixed with "/topic".
config.enableSimpleBroker("/topic");
// Designate the "/app" prefix to filter destinations targeting application annotated methods.
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// Registers the "/gs-guide-websocket" endpoint, enabling SockJS fallback options so that alternate transports may be used if WebSocket is not available.
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
}
Simple Example with Data Flow Explanation
Controller:
@Controller
public class GreetingController {
@MessageMapping("/hello") // 1. Client sends message to "/app/hello"
@SendTo("/topic/greetings") // 3. Server sends greeting to "/topic/greetings"
public String greet(String message) throws Exception {
Thread.sleep(1000); // Simulate processing time
return "Hello, " + message + "!"; // 2. Server processes the message
}
}
Client-Side (JavaScript):
var stompClient = null;
function connect() {
var socket = new SockJS('/gs-guide-websocket'); // Connect to the WebSocket endpoint
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) { // 4. Client listens on "/topic/greetings"
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function sendName() {
stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
Data Flow:
- Client to Server: The client sends a message to the server through the WebSocket connection, targeting the destination
/app/hello
. - Server Processing: The
@MessageMapping
annotation on thegreet()
method in theGreetingController
handles this message. It processes the message (e.g., adding "Hello, " to the message). - Server to Client (Broadcast): The
@SendTo
annotation designates the destination/topic/greetings
where the processed message (“Hello, [message]!”) should be sent. All subscribed clients receive this greeting. - Client Receives: The client, which has subscribed to
/topic/greetings
, receives the message from the server and displays it on the web page.
Key Points
- @EnableWebSocketMessageBroker: Enables WebSocket message handling and configures a message broker.
- @MessageMapping: Maps a message to a controller method.
- @SendTo: Specifies the destination where the response message should be sent.
- configureMessageBroker: Configures the message broker to handle messages with the “/topic” prefix and directs application messages to methods annotated with @MessageMapping.
- registerStompEndpoints: Registers a WebSocket endpoint at “/gs-guide-websocket” and enables SockJS as a fallback option.
By understanding these concepts and building upon the provided examples, you can create powerful real-time web applications with Spring WebSocket.
Discover more from GhostProgrammer - Jeff Miller
Subscribe to get the latest posts sent to your email.